时间:2020-12-15 00:38:11 | 栏目:C代码 | 点击:次
inRange函数
void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst);
src:输入图像;
lowerb:下边界数组,阈值下限;
upperb:上边界数组,阈值上限;
dst:输出图像;
颜色范围如图:
示例:
捕获摄像头中的黄色方块
#include<opencv2/opencv.hpp> using namespace cv; int main() { VideoCapture capture; capture.open(0); if(!capture.isOpened()) { printf("can not open video file \n"); return -1; } Mat frame, dst; Mat kernel; //开操作处理 kernel = getStructuringElement(MORPH_RECT, Size(5, 5)); namedWindow("input", CV_WINDOW_AUTOSIZE); namedWindow("output", CV_WINDOW_AUTOSIZE); std::vector<std::vector<Point>> contours; std::vector<Vec4i> hireachy; Rect rect; Point2f center; float radius=20; while (capture.read(frame)) { //blur(frame, dst, Size(5,5)); inRange(frame, Scalar(0,80,80), Scalar(50,255,255), dst); //开操作 morphologyEx(dst,dst,MORPH_OPEN,kernel); //获取边界 findContours(dst, contours, hireachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0,0)); //框选面积最大的边界 if (contours.size() > 0) { double maxArea=0; for (int i = 0; i < contours.size(); i++) { double area = contourArea(contours[static_cast<int>(i)]); if (area > maxArea) { maxArea = area; rect = boundingRect(contours[static_cast<int>(i)]); minEnclosingCircle(contours[static_cast<int>(i)], center, radius); } } } //矩形框 //rectangle(frame,rect, Scalar(0,255,0),2); //圆形框 circle(frame, Point(center.x,center.y), (int)radius, Scalar(0,255,0), 2); imshow("input", frame); imshow("output", dst); waitKey(100); } capture.release(); return 0; }
关于颜色范围的选取:
有朋友问颜色范围的事,比如我们选择某个偏红色的范围,如色环图中这个区间即BGR(0,128,255)到BGR(255,0,213);则B、G、R这三个通道的范围分别为0-255,0-128,213-255。因此阈值下限lowerb=Scalar(0,0,213),阈值上限upperb=Scalar(255,128,255)。