同时识别三种颜色—— opencv
Posted bjxqmy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同时识别三种颜色—— opencv相关的知识,希望对你有一定的参考价值。
要点:
1.分别识别图片中的黄蓝红三色
//创建三个 Mat 来分别存储识别黄蓝红三色并二值化后的图片
Mat yellowImg, blueImg, redImg;
for (int i = 0; i < 3; i++){
switch (i){
case 0: //黄色
minH = 16;
maxH = 35;
minS = 160;
maxS = 255;
minV = 50;
maxV = 255;
// inRange(原图像, 最小值的范围, 最大值的范围, 输出图像);
//将图像二值化,即输出图像是黑白二值图像,其中 最小值<=像素点<=最大值 的像素点是白色
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), yellowImg);
break;
case 1: //蓝色
minH = 70;
maxH = 120;
minS = 150;
maxS = 255;
minV = 50;
maxV = 255;
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), blueImg);
break;
case 2: //红色
minH = 0;
maxH = 15;
minS = 160;
maxS = 255;
minV = 50;
maxV = 255;
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), redImg);
break;
default:
printf("颜色标志输入错误
");
}
}
2.合并三张图片
Mat resultImg;
Mat yeBluImg;
//图像算数运算————合并(或)
bitwise_or(yellowImg, blueImg, yeBluImg);
bitwise_or(yeBluImg, redImg, resultImg);
3.图片去噪
//开操作 (去除一些噪点) 如果二值化后图片干扰部分依然很多,增大下面的size
Mat eleOpen = getStructuringElement(MORPH_RECT, Size(6, 6));//返回指定形状和尺寸的结构元素
morphologyEx(resultImg, resultImg, MORPH_OPEN, eleOpen);
代码示例:
#include<opencv.hpp>
using namespace cv;
using namespace std;
int main(){
Mat srcImg = imread("C:/Users/齐明洋/Desktop/tem2.png");
Mat hsvImg;
//将RGB颜色空间转换为HSV颜色空间
cvtColor(srcImg, hsvImg, COLOR_BGR2HSV);
int minH = 0;
int maxH = 0;
int minS = 0;
int maxS = 0;
int minV = 0;
int maxV = 0;
Mat yellowImg, blueImg, redImg;
for (int i = 0; i < 3; i++){
switch (i){
case 0: //黄色
minH = 16;
maxH = 35;
minS = 160;
maxS = 255;
minV = 50;
maxV = 255;
// inRange(原图像, 最小值的范围, 最大值的范围, 输出图像);
//将图像二值化,即输出图像是黑白二值图像,其中 最小值<=像素点<=最大值 的像素点是白色
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), yellowImg);
break;
case 1: //蓝色
minH = 70;
maxH = 120;
minS = 150;
maxS = 255;
minV = 50;
maxV = 255;
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), blueImg);
break;
case 2: //红色
minH = 0;
maxH = 15;
minS = 160;
maxS = 255;
minV = 50;
maxV = 255;
inRange(hsvImg, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), redImg);
break;
default:
printf("颜色标志输入错误
");
}
}
Mat resultImg;
Mat yeBluImg;
//图像算数运算————合并(或)
bitwise_or(yellowImg, blueImg, yeBluImg);
bitwise_or(yeBluImg, redImg, resultImg);
//开操作 (去除一些噪点) 如果二值化后图片干扰部分依然很多,增大下面的size
Mat eleOpen = getStructuringElement(MORPH_RECT, Size(6, 6));//返回指定形状和尺寸的结构元素
morphologyEx(resultImg, resultImg, MORPH_OPEN, eleOpen);
imshow("原始图片", srcImg);
imshow("识别结果", resultImg);
waitKey(0);
return 0;
}
运行结果:
以上是关于同时识别三种颜色—— opencv的主要内容,如果未能解决你的问题,请参考以下文章