opencv再学习之路(四)---色彩分割得到二值图像

1. 通过给RGB图像的三个分量设定阈值,实现特定颜色的分离,并转换为二值图像

 1 #include"stdafx.h"
 2 #include<opencv2opencv.hpp>
 3 #include<opencv2highguihighgui.hpp>
 4 #include<iostream>
 5 #include<Windows.h>
 6 #include<time.h>
 7 
 8 using namespace std;
 9 using namespace cv;
10 
11 
12 int main()
13 {
14     // 图片保存参数
15     vector<int> compression_params;
16     compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
17     compression_params.push_back(9);
18 
19     Mat src = imread("05.jpg");
20 
21     Mat binary = Mat::zeros(src.size(), CV_8UC1);
22 
23     // 色彩分割得到二值图像
24     for (int i = 0; i < src.rows; i++)
25     {
26         for (int j = 0; j < src.cols; j++)
27         {
28             int b = (int)(src.at<Vec3b>(i,j)[0]);    // 提取蓝色分量
29             int g = (int)(src.at<Vec3b>(i,j)[1]);    // 提取绿色分量
30             int r = (int)(src.at<Vec3b>(i,j)[2]);    // 提取红色分量
31             if (b < 100 && g < 100 && r < 100 )
32             {
33                 binary.at<uchar>(i,j) = 0;
34             }
35             else
36             {
37                 binary.at<uchar>(i,j) = 255;
38             }
39         }
40     }
41 
42     imshow("原图",src);
43     imshow("取特定色彩的二值化图像",binary);
44     imwrite("取特定色彩的二值化图像.jpg",binary,compression_params);
45 
46     waitKey(0);
47     return 0;
48 
49 }
原文地址:https://www.cnblogs.com/zhp218/p/8530753.html