Last active
September 29, 2018 13:30
-
-
Save atduskgreg/8e23a0a2301119de6850 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gab.opencv.*; | |
import org.opencv.imgproc.Imgproc; | |
import org.opencv.core.MatOfPoint2f; | |
import org.opencv.core.Point; | |
import org.opencv.core.Size; | |
import org.opencv.core.Mat; | |
import org.opencv.core.CvType; | |
OpenCV opencv; | |
ArrayList<PVector> inputPoints; | |
boolean perspectiveWarped = false; | |
void setup() { | |
opencv = new OpenCV(this, "test.png"); | |
inputPoints = new ArrayList<PVector>(); | |
size(opencv.width, opencv.height); | |
} | |
void draw() { | |
if (inputPoints.size() >= 4) { | |
if (!perspectiveWarped) { | |
opencv.setGray(warpPerspective(opencv.getGray(), inputPoints, width, height)); | |
perspectiveWarped = true; | |
} | |
} | |
image(opencv.getOutput(), 0, 0); | |
noFill(); | |
stroke(255); | |
beginShape(); | |
for (PVector p : inputPoints) { | |
vertex(p.x, p.y); | |
ellipse(p.x, p.y, 3, 3); | |
} | |
endShape(); | |
} | |
void mousePressed() { | |
inputPoints.add(new PVector(mouseX, mouseY)); | |
} | |
Mat warpPerspective(Mat warped, ArrayList<PVector> points, int w, int h) { | |
Mat transform = getPerspectiveTransformation(points, w, h); | |
Mat unwarped = new Mat(w, h, CvType.CV_8UC1); | |
Imgproc.warpPerspective(warped, unwarped, transform, new Size(w, h)); | |
return unwarped; | |
} | |
Mat getPerspectiveTransformation(ArrayList<PVector> points, int w, int h) { | |
Point[] canonicalPoints = new Point[4]; | |
canonicalPoints[0] = new Point(w, 0); | |
canonicalPoints[1] = new Point(0, 0); | |
canonicalPoints[2] = new Point(0, h); | |
canonicalPoints[3] = new Point(w, h); | |
MatOfPoint2f canonicalMarker = new MatOfPoint2f(); | |
canonicalMarker.fromArray(canonicalPoints); | |
Point[] p = new Point[4]; | |
for (int i = 0; i < 4; i++) { | |
p[i] = new Point(points.get(i).x, points.get(i).y); | |
} | |
MatOfPoint2f marker = new MatOfPoint2f(p); | |
return Imgproc.getPerspectiveTransform(marker, canonicalMarker); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment