OpenCV getPerspectiveTransform和warpPerspective Java

我目前有一个ArrayList ,它存储图像的轮廓,并检索出最大的轮廓,这是我的warpPerspective的目标。

 List contours = new ArrayList(); Imgproc.findContours(matOut, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); sort(contours); MatOfPoint2f m2f = MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(m2f, true); MatOfPoint2f approx = new MatOfPoint2f(); Imgproc.approxPolyDP(m2f, approx, arc*0.02, true); 

我在如何使用getPerspectiveTransform然后应用warpPerspective来更改图像以使其适合450×450图像时遇到问题。

我在python中找到了一个相当不错的例子,但是我对它不是很熟悉有人可以解释一下我将如何在java中进行纠正?

 def rectify(h): ''' this function put vertices of square we got, in clockwise order ''' h = h.reshape((4,2)) hnew = np.zeros((4,2),dtype = np.float32) add = h.sum(1) hnew[0] = h[np.argmin(add)] hnew[2] = h[np.argmax(add)] diff = np.diff(h,axis = 1) hnew[1] = h[np.argmin(diff)] hnew[3] = h[np.argmax(diff)] return hnew 

这是源链接: https : //github.com/abidrahmank/OpenCV2-Python/blob/master/OpenCV_Python_Blog/sudoku_v_0.0.6/sudoku.py

简介 :要使用wrapPerspective,我们需要使用getPerspectiveTransform来计算包裹垫:Mat src和Mat dst。 那些是你的轮廓的src(左下角,右下角,左上角,右上角)的MarOfPoints2f和相应的mat dst(0,0; ​​0,449; 449,0; 449,449)(所以图像将是450×450 – 如果这是错的,请纠正我)。

用于opencv 3的Java 解决方案是:

  1. 获得点排序有矩形轮廓为MatOfPoints2f,我们需要对点进行排序,如上所示:

     //calculate the center of mass of our contour image using moments Moments moment = Imgproc.moments(approx.get(0)); int x = (int) (moment.get_m10() / moment.get_m00()); int y = (int) (moment.get_m01() / moment.get_m00()); //SORT POINTS RELATIVE TO CENTER OF MASS Point[] sortedPoints = new Point[4]; double[] data; int count = 0; for(int i=0; i x && datay < y){ sortedPoints[1]=new Point(datax,datay); count++; }else if (datax < x && datay > y){ sortedPoints[2]=new Point(datax,datay); count++; }else if (datax > x && datay > y){ sortedPoints[3]=new Point(datax,datay); count++; } } 
  2. 准备Mat src和det

      MatOfPoint2f src = new MatOfPoint2f( sortedPoints[0], sortedPoints[1], sortedPoints[2], sortedPoints[3]); MatOfPoint2f dst = new MatOfPoint2f( new Point(0, 0), new Point(450-1,0), new Point(0,450-1), new Point(450-1,450-1) ); 
  3. 使用getPerspectiveTransform和wrapPrespective

      Mat warpMat = Imgproc.getPerspectiveTransform(src,dst); //This is you new image as Mat Mat destImage = new Mat(); Imgproc.warpPerspective(originalImg, destImage, warpMat, originalImg.size()); 

我刚刚完成了类似的项目,所以我确信这可以做得更好但是如果有人需要的话,这是一个有效的解决方案。