本文共 1903 字,大约阅读时间需要 6 分钟。
对亮背景的图片,会把整个图片作为最大轮廓找出来。请看下面的代码和示意图,Canny出来的图片经过img=255-img处理,这样背景是亮的,矩形轮廓是黑色的嵌在亮背景里。结果找出来的最大轮廓是整幅图(围在整个图周围的白色矩形是最大的轮廓),示意图里左边是输入findContours 处理的原始图,右边是画出来的轮廓图。代码也列在下面。
#include "opencv2/core.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "iostream"#includeusing 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 > 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"#includeusing 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 > 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;}
转载地址:http://oemqf.baihongyu.com/