相对于之前使用inrange()函数的的两篇文章,这篇使用了通道相减的方式,来确定目标的颜色,也算是一个比较简单的方法吧,
免去了一直修改颜色参数的问题,后期的准确度就是靠对图像的优化和处理所决定的
放代码
Mat picture, Dealed_pict,Bright_pict; vector<Mat>channels; int BrightValue = 80; vector<vector<Point> > contours; vector<Vec4i> hierarchy; int main() { namedWindow("识别颜色", WINDOW_NORMAL); VideoCapture capture(0); while (1) { capture >> picture; split(picture, channels); Dealed_pict = channels.at(2) - channels.at(0); threshold(Dealed_pict, Dealed_pict, 120, 255, THRESH_BINARY); Mat element = getStructuringElement(MORPH_ELLIPSE,Size(4,4)); dilate(Dealed_pict, Dealed_pict, element); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(Dealed_pict, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); RotatedRect box; double area = 0; for (int i = 0; i < contours.size(); i++) { if (contourArea(contours[i]) > area) { area = contourArea(contours[i]); box = minAreaRect(contours[i]); } } Point2f vertex[4]; box.points(vertex); for (int i = 0; i < 4; i++) { line(picture, vertex[i], vertex[(i + 1) % 4], Scalar(100, 200, 300), 2, LINE_AA); } imshow("识别颜色", Dealed_pict); imshow("原图",picture); waitKey(1); } return 0; }