一、简介
二、轮廓最小外接矩形的绘制
1 #include "opencv2/opencv.hpp" 2 using namespace cv; 3 4 void main() 5 { 6 //轮廓最小外接矩形的绘制 7 Mat srcImg = imread("E://00.png"); 8 Mat dstImg = srcImg.clone(); 9 cvtColor(srcImg, srcImg, CV_BGR2GRAY);10 threshold(srcImg, srcImg, 100, 255, CV_THRESH_BINARY); //二值化11 imshow("threshold", srcImg);12 13 vector> contours;14 vector hierarcy;15 findContours(srcImg, contours, hierarcy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);16 vector boundRect(contours.size()); //定义外接矩形集合17 vector box(contours.size()); //定义最小外接矩形集合18 Point2f rect[4];19 for(int i=0; i
三、粗略计算物体像素长宽
1 #include "opencv2/opencv.hpp" 2 #include3 using namespace std; 4 using namespace cv; 5 6 void main() 7 { 8 Mat srcImg = imread("E://cup.jpg"); 9 imshow("src", srcImg);10 Mat dstImg = srcImg.clone();11 medianBlur(srcImg, srcImg, 5);12 GaussianBlur(srcImg, srcImg, Size(3, 3), 0, 0);13 cvtColor(srcImg, srcImg, CV_BGR2GRAY);14 threshold(srcImg, srcImg, 100, 255, CV_THRESH_BINARY_INV); //INV是因为背景白色,物体黑色,需要反转一下15 imshow("threshold", srcImg);16 17 vector > contours;18 vector hierarcy;19 20 findContours(srcImg, contours, hierarcy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);21 cout<<"num="< < boundRect(contours.size());23 vector box(contours.size());24 Point2f rect[4];25 for(int i=0; i
四、倾斜物体矫正提取
1 #include "opencv2/opencv.hpp" 2 #include3 using namespace std; 4 using namespace cv; 5 6 void main() 7 { 8 Mat srcImg = imread("E://qrcode.jpg"); 9 imshow("src", srcImg);10 Mat dstImg = srcImg.clone();11 GaussianBlur(srcImg, srcImg, Size(3, 3), 0, 0);12 cvtColor(srcImg, srcImg, CV_BGR2GRAY);13 Canny(srcImg, srcImg, 100, 200);//因为原图比较复杂,所以需要将canny的值调大,去除不想要的成分14 //threshold(srcImg, srcImg, 100, 255, CV_THRESH_BINARY_INV); //二值化也可以实现canny效果,不过在本例中杂絮较多15 imshow("canny", srcImg);16 Mat element = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1)); //定义结构元素17 dilate(srcImg, srcImg, element); //膨胀18 imshow("dilate", srcImg);19 erode(srcImg, srcImg, element);20 imshow("erode", srcImg);21 22 vector > contours;23 vector hierarcy;24 findContours(srcImg, contours, hierarcy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);25 vector boundRect(contours.size());26 vector box(contours.size());27 Point2f rect[4];28 for(int i=0; i