我能夠檢測圖像中最大的方形/矩形(綠色)。但是,我想將圖像中檢測到的最大方形/矩形轉換爲新圖像(存儲在新的Mat中)。OpenCV Android使用最大輪廓的邊緣創建新圖像
這裏的這個功能上有最大的矩形/平方米的返回圖像:http://img153.imageshack.us/img153/9308/nn4w.png
這裏是我到目前爲止的代碼:
private Mat findLargestRectangle(Mat original_image) {
Mat imgSource = original_image;
//convert the image to black and white
Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
//convert the image to black and white does (8 bit)
Imgproc.Canny(imgSource, imgSource, 50, 50);
//apply gaussian blur to smoothen lines of dots
Imgproc.GaussianBlur(imgSource, imgSource, new Size(5, 5), 5);
//find the contours
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;
MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
MatOfPoint2f approxCurve = new MatOfPoint2f();
Mat 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);
//compare this contour to the previous largest contour found
if (contourarea > maxArea) {
//check if this contour is a square
MatOfPoint2f new_mat = new MatOfPoint2f(temp_contour.toArray());
int contourSize = (int)temp_contour.total();
Imgproc.approxPolyDP(new_mat, approxCurve, contourSize*0.05, true);
if (approxCurve.total() == 4) {
maxArea = contourarea;
maxAreaIdx = idx;
largest_contours.add(temp_contour);
largest_contour = temp_contour;
}
}
}
MatOfPoint temp_largest = largest_contours.get(largest_contours.size()-1);
largest_contours = new ArrayList<MatOfPoint>();
largest_contours.add(temp_largest);
Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB);
Imgproc.drawContours(imgSource, largest_contours, -1, new Scalar(0, 255, 0), 1);
//create the new image here using the largest detected square
Toast.makeText(getApplicationContext(), "Largest Contour: ", Toast.LENGTH_LONG).show();
return imgSource;
}
變量largest_contours是MatOfPoint列表但只包含最大輪廓,還存儲在largest_contour變量中。我怎樣才能從最大的輪廓創造一個新的形象?
我正在使用的Android OpenCV的和有用於檢測圖像的幾個教程,但不完全是關於如何使用Imgproc.warpPerspective()
謝謝!
當你說「做一個新的形象」時,你是什麼意思?這個「新形象」包含什麼? – Aurelius
你好@Aurelius,這是我試圖實現http://stackoverflow.com/questions/17512234/android-opencv-find-largest-square-or-rectangle。我幾個星期前發佈了這個,現在我可以檢測圖像中最大的方形輪廓,我想裁剪該圖像並創建一個新的。 –
我成功使用此代碼找出最大的矩形。我也找到了一種方法來保存最終的圖像。由此產生的圖像黑白。我怎樣才能防止呢?我希望它被着色。 – TharakaNirmana