有一个已知的面积作为标定,比例法来计算,颜色识别inrange()函数用来区分不同的图像,
OpenCv麻烦的就是得自己去修改参数
Mat g_srcImage2, g_grayImage2; vector<Vec4i>g_vHierarchy2; Mat g_srcImage, g_grayImage; int main() { VideoCapture capture(0); while (1) { //载入源图像 system("color 02"); capture >> g_srcImage;// = imread("D:\6666.jpg"); imshow("原图", g_srcImage); capture >> g_srcImage2;// = imread("D:\6666.jpg"); cvtColor(g_srcImage2, g_grayImage2, COLOR_BGR2HSV);//对图像HSV处理 inRange(g_grayImage2, Scalar(0, 0, 0), Scalar(180, 255, 46), g_grayImage2);//颜色识别--黑色的标定面积 imshow("黑色的标定面积", g_grayImage2); ////////////////////////////寻找最小矩形边框////////////////////////////////////////////////////////// vector<vector<Point>>contours2; vector<Vec4i>hierarchy2; findContours(g_grayImage2, contours2, hierarchy2, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); RotatedRect box2; double area2 = 0; for (int i = 0; i < contours2.size(); i++) { if (contourArea(contours2[i]) > area2) { box2 = minAreaRect(contours2[i]); area2 = contourArea(contours2[i]); } } Point2f vertex2[4]; box2.points(vertex2); for (int i = 0; i < 4; i++) { box2.size.width; line(g_grayImage2, vertex2[i], vertex2[(i + 1) % 4], Scalar(100, 200, 211), 2, LINE_AA); } cvtColor(g_srcImage, g_grayImage, COLOR_BGR2HSV);//对图像HSV处理 inRange(g_grayImage, Scalar(44, 86, 20), Scalar(111, 255, 255), g_grayImage);//电路板识别 //寻找最小矩形边框 vector<vector<Point>>contours; vector<Vec4i>hierarchy; findContours(g_grayImage, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); RotatedRect box; double area = 0; for (int i = 0; i < contours.size(); i++) { if (contourArea(contours[i]) > area) { box = minAreaRect(contours[i]); area = contourArea(contours[i]); } } Point2f vertex[4]; box.points(vertex); for (int i = 0; i < 4; i++) { box.size.width; line(g_grayImage, vertex[i], vertex[(i + 1) % 4], Scalar(100, 200, 211), 2, LINE_AA); system("color 02"); cout << "宽度" << box.size.width / box2.size.width * 30 << endl << "长度" << box.size.height / box2.size.height * 30 << endl << "面积" << endl << box.size.height * box.size.width / box2.size.height / box2.size.width * 900 << endl; } waitKey(50); } return 0; }