How to straight an image by selecting four points in an Image?

試著忘記壹切 提交于 2021-02-16 05:09:42

问题


I want to straight an image by selecting four points in the image using getPerspectiveTransform() method of opencv in java. I know it can be done using with opencv in python: getPerspectiveTransform. If anyone used this to achieve image straightening ..please help.


回答1:


There is perspective transformation which can be used to achieve quad to quad conversion. In OpenCV, there are mainly two methods to achieve getPerspectiveTransformation() and warpPerspective() method.

Here is a sample code to achieve Image Straightening:

First get four quadrilinear points in source image

Mat srcImage = Imgcodecs.imread("input.png");
Mat destImage = new Mat(500, 700, srcImage.type());
Mat src = new MatOfPoint2f(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3), new Point(x4, y4));
Mat dst = new MatOfPoint2f(new Point(0, 0), new Point(destImage.width() - 1, 0), new Point(destImage.width() - 1, destImage.height() - 1), new Point(0, destImage.height() - 1));

Getting transformation metrix

Mat transform = Imgproc.getPerspectiveTransform(src, dst);
Imgproc.warpPerspective(srcImage, destImage, transform, destImage.size());

you will get transformed straighten image.

I have tested this code on this image.

and The resulted image is




回答2:


Try this:

Mat mat=Highgui.imread("inputImage.jpg");
Mat src_mat=new Mat(4,1,CvType.CV_32FC2);
Mat dst_mat=new Mat(4,1,CvType.CV_32FC2);

// Keypoint location on source image
src_mat.put(0,0,407.0,74.0,1606.0,74.0,420.0,2589.0,1698.0,2589.0);
// Desired keypoint location after straigting
dst_mat.put(0,0,0.0,0.0,1600.0,0.0, 0.0,2500.0,1600.0,2500.0);
Mat perspectiveTransform=Imgproc.getPerspectiveTransform(src_mat, dst_mat);

Mat dst=mat.clone();

Imgproc.warpPerspective(mat, dst, perspectiveTransform, new Size(1600,2500));
Highgui.imwrite("resultImage.jpg", dst);

Original thread: Android OpenCV getPerspectiveTransform and warpPerspective



来源:https://stackoverflow.com/questions/36054795/how-to-straight-an-image-by-selecting-four-points-in-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!