我很兴奋地回答我的问题!这很容易,但当你刚开始使用不太适当的相关文档时,就会发生这种情况。
我努力尝试获取一般矩形的角落,但在openCV实现中没有定义,因此几乎是不可能的。
我遵循stackoverflow上最大正方形检测的标准代码,可以使用approxCurve轻松找到角落。
//将图像转换为黑白
Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
Imgproc.Canny(imgSource, imgSource, 50, 50);
Imgproc.GaussianBlur(imgSource, imgSource, new org.opencv.core.Size(5, 5), 5);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
double maxArea = -1;
int maxAreaIdx = -1;
Log.d("size",Integer.toString(contours.size()));
MatOfPoint temp_contour = contours.get(0);
MatOfPoint2f approxCurve = new MatOfPoint2f();
MatOfPoint largest_contour = contours.get(0);
List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
for (int idx = 0; idx < contours.size(); idx++) {
temp_contour = contours.get(idx);
double contourarea = Imgproc.contourArea(temp_contour);
if (contourarea > maxArea) {
MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() );
int contourSize = (int)temp_contour.total();
MatOfPoint2f approxCurve_temp = new MatOfPoint2f();
Imgproc.approxPolyDP(new_mat, approxCurve_temp, contourSize*0.05, true);
if (approxCurve_temp.total() == 4) {
maxArea = contourarea;
maxAreaIdx = idx;
approxCurve=approxCurve_temp;
largest_contour = temp_contour;
}
}
}
Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB);
sourceImage =Highgui.imread(Environment.getExternalStorageDirectory().
getAbsolutePath() +"/scan/p/1.jpg");
double[] temp_double;
temp_double = approxCurve.get(0,0);
Point p1 = new Point(temp_double[0], temp_double[1]);
temp_double = approxCurve.get(1,0);
Point p2 = new Point(temp_double[0], temp_double[1]);
temp_double = approxCurve.get(2,0);
Point p3 = new Point(temp_double[0], temp_double[1]);
temp_double = approxCurve.get(3,0);
Point p4 = new Point(temp_double[0], temp_double[1]);
List<Point> source = new ArrayList<Point>();
source.add(p1);
source.add(p2);
source.add(p3);
source.add(p4);
Mat startM = Converters.vector_Point2f_to_Mat(source);
Mat result=warp(sourceImage,startM);
return result;
透视变换所使用的函数如下:
public Mat warp(Mat inputMat,Mat startM)