對亮背景的圖片,會把整個圖片作爲最大輪廓找出來。請看下面的代碼和示意圖,Canny出來的圖片經過img=255-img處理,這樣背景是亮的,矩形輪廓是黑色的嵌在亮背景裏。結果找出來的最大輪廓是整幅圖(圍在整個圖周圍的白色矩形是最大的輪廓),示意圖裏左邊是輸入findContours 處理的原始圖,右邊是畫出來的輪廓圖。代碼也列在下面。
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "iostream"
#include <cstdio>
using namespace std;
using namespace cv;
int main()
{
Mat imgS = imread("../images/a2.png", 0);
Mat img;
GaussianBlur(imgS, img, Size(3, 3), 0);
Canny(img, img, 80, 160);
img = 255 - img;
namedWindow("Image to findContours", WINDOW_NORMAL);
imshow("Image to findContours", img );
vector<vector<Point>> contours;
findContours(img, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point());
Mat imageContours = Mat::zeros(img.size(), CV_8UC1);
drawContours(imageContours, contours,-1, Scalar(255), 16, 8 );
namedWindow("Contours Image", WINDOW_NORMAL);
imshow("Contours Image", imageContours);
imwrite("../images/contours.png", imageContours);
waitKey(0);
return 0;
}
Canny出來的圖片不經過img=255-img反色處理,背景就是暗的。在暗背景上findContours則不會將整個圖片作爲最大的輪廓。下面的將img=255-img 註釋掉之後的處理結果,圖片和代碼都列出來,上圖中圍在整個圖四周的輪廓沒有出現。
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "iostream"
#include <cstdio>
using namespace std;
using namespace cv;
int main()
{
Mat imgS = imread("../images/a2.png", 0);
Mat img;
GaussianBlur(imgS, img, Size(3, 3), 0);
Canny(img, img, 80, 160);
//img = 255 - img;
namedWindow("Image to findContours", WINDOW_NORMAL);
imshow("Image to findContours", img );
vector<vector<Point>> contours;
findContours(img, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point());
Mat imageContours = Mat::zeros(img.size(), CV_8UC1);
drawContours(imageContours, contours,-1, Scalar(255), 16, 8 );
namedWindow("Contours Image", WINDOW_NORMAL);
imshow("Contours Image", imageContours);
imwrite("../images/contours.png", imageContours);
waitKey(0);
return 0;
}