前言
这篇文章主要讲述opencv中红色杯盖的检测。
一、检测红色杯盖
//第三题 检测红色杯盖
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// VideoCapture cap(0);
double scale = 0.5;
//0-188
//肤色
double i_minH = 150;
double i_maxH = 255;
//0-255
double i_minS = 150;
double i_maxS = 255;
//0-255
double i_minV = 150;
double i_maxV = 255;
while (1)
{
Mat frame;
Mat hsvMat;
Mat detectMat;
frame= imread("C://Users//john//Desktop//2.jpg");;
Size ResImgSiz = Size(frame.cols*scale, frame.rows*scale);
Mat rFrame = Mat(ResImgSiz, frame.type());
resize(frame, rFrame, ResImgSiz, INTER_LINEAR);
cvtColor(rFrame, hsvMat, COLOR_BGR2HSV);
rFrame.copyTo(detectMat);
cv::inRange(hsvMat, Scalar(i_minH, i_minS, i_minV), Scalar(i_maxH, i_maxS, i_maxV), detectMat);
vector<vector<Point>> contours;
vector<Vec4i> hirearchy;
findContours(detectMat, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
int num = contours.size();
Point2f rect[4];
for (int i = 0; i < num; i++)
{
RotatedRect rbox = minAreaRect(contours[i]);
///cout << rbox << endl;
int area = contourArea(contours[i]);//计算轮廓面积
rbox.points(rect); //把最小外接矩形四个端点复制给rect数组
if (area >= 40)
{
drawContours(detectMat, contours, i, Scalar(255, 0, 0), -1, 8);
for (int j = 0; j < 4; j++)
{
line(rFrame, rect[j], rect[(j + 1) % 4], Scalar(255, 255, 255), 2, 8); //绘制最小外接矩形每条边
}
}
}
imshow("while: in the range ", detectMat);
imshow("frame", rFrame);
waitKey(30);
}
}
总结
1.代码可以直接运行,如有不懂请留言哦。