opencv检测物体颜色
#include<opencv2/opencv.hpp> #include<opencv2/opencv_modules.hpp> #include<iostream> #include<math.h> using namespace cv; using namespace std; Mat src, dst, binout, src_gray; int Threshold = 140; void jdge_color(vector<int> colovec); int main() { //输入图像并转化为灰度 src = imread("E://2.png"); if (src.empty()) { printf("src couldn't be loaded..."); return -1; } imshow("input", src); cvtColor(src, src_gray, COLOR_BGR2GRAY); medianBlur(src_gray, src_gray, 21); blur(src_gray, src_gray, Size(21, 21)); //设置阈值后执行CallBack() namedWindow("output"); //createTrackbar("Threshold", "output", &Threshold, 255, CallBack); //二值化 threshold(src_gray, binout, Threshold, 255, THRESH_BINARY); //Canny(src_gray, binout, Threshold, Threshold * 2); imshow("binary", binout); //寻找边缘 vector<vector<Point>> contours; vector<Vec4i> hierachy; findContours(binout, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); //得到矩形框相关参数 vector<vector<Point>> polies(contours.size());//减少后的多边形边缘上的点 vector<Rect> rects(contours.size());//矩形框 for (size_t i = 0; i < contours.size(); i++) { approxPolyDP(Mat(contours[i]), polies[i], 3, true);//减少多边形边缘点 rects[i] = boundingRect(polies[i]); } //绘制他们 Point2f pts[4]; for (size_t i = 0; i < contours.size(); i++) { Mat matHsv; Mat imgThresholded; Scalar scalar; Mat cut = src(rects[i]); cvtColor(cut, matHsv, COLOR_BGR2HSV); imshow("hsv.jpg", matHsv); scalar = cut.at<Vec3b>(cut.rows/2, cut.cols/2); int a = (int)scalar.val[1]; rectangle(src, rects[i], Scalar(0,0,0), 2);//画矩形框 //mage_rect.push_back(src(rects[i])); } imshow("output", src); waitKey(0); return 0; }
注明:有部分代码来源于网络,如果是你写的,请留言让我注明一下原作者!