我正在尝试对四边形物体进行自动透视校正。
当我使用getPerspectiveTransform函数时,我收到错误:
OpenCV Error: Assertion failed (src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4) in cv::getPerspectiveTransform
这是我的代码:
Mat originalMat = new Mat();
originalMat=Imgcodecs.imread("photo.jpg");
Mat binaryMat = new Mat();
Imgproc.cvtColor(originalMat, binaryMat, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(binaryMat, binaryMat, 0 , 255, Imgproc.THRESH_OTSU | Imgproc.THRESH_BINARY);
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(binaryMat.clone(), contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
int largestContour=0, tempContour, largestContourIndex=0;
if(contours.size()>1)
for (int i = 0; i < contours.size(); i++) {
MatOfPoint2f mop2f = new MatOfPoint2f();
contours.get(i).convertTo(mop2f, CvType.CV_32F);
RotatedRect rect = Imgproc.minAreaRect(mop2f);
tempContour = rect.boundingRect().width * rect.boundingRect().height;
if(largestContour < tempContour){
largestContour = tempContour;
largestContourIndex = i;
}
}
Rect rectangle = Imgproc.boundingRect(contours.get(largestContourIndex));
Point[] boundingRectPoints = new Point[4];
boundingRectPoints[0] = new Point(rectangle.x,rectangle.y);
boundingRectPoints[1] = new Point((rectangle.x+rectangle.width),rectangle.y);
boundingRectPoints[2] = new Point(rectangle.x+rectangle.width,rectangle.y+rectangle.height);
boundingRectPoints[3] = new Point(rectangle.x,rectangle.y+rectangle.height);
MatOfPoint boundingRTMatOfPoint = new MatOfPoint(boundingRectPoints);
Mat beforeCorrectionMat = new Mat();
Mat afterCorrectionMat = new Mat();
contours.get(largestContourIndex).convertTo(beforeCorrectionMat, CvType.CV_32FC2);
boundingRTMatOfPoint.convertTo(afterCorrectionMat, CvType.CV_32FC2);
Mat transmtx = Imgproc.getPerspectiveTransform( beforeCorrectionMat, afterCorrectionMat);
Mat transformed = Mat.zeros(originalMat.height(), originalMat.width(), CvType.CV_8UC1);
Imgproc.warpPerspective(originalMat, transformed, transmtx, originalMat.size());
我在这里找到了类似的问题:Assertion failed when I'm trying to use getPerspectiveTransform on Android-NDK to transform a perspective image
但它对我没有帮助。 我会非常感谢任何帮助。