任务2: 肤色检测

来源:互联网 发布:鸡兔同笼java语言编程 编辑:程序博客网 时间:2024/04/18 15:31
#include <opencv2/core/core.hpp>   #include <opencv2/highgui/highgui.hpp>  #include <opencv2/imgproc/imgproc.hpp>  //转换颜色空间需要的头文件#include <iostream>  #include <vector>  using namespace std;using namespace cv;int main(){    Mat Image = imread("E:\\opencvTest\\renshou.jpg");//读取图片    imshow("原图", Image);//显示原图片    cvtColor(Image, Image, CV_BGR2YCrCb);//转换颜色空间 RGB类型转换为YCrCb类型(因为opencv默认的图片通道顺序是BGR而不是RGB)                                         //目的是减少图像中颜色的数目,主要是为了降低分析的复杂度    vector<Mat> channels;//创建一个Mat类型的channels数组    //把一个3通道图像转换成3个单通道图像(即三个都是灰度图)    split(Image, channels);//分割颜色通道放在数组channels中    Mat Y, Cr, Cb;    Y = channels.at(0);    Cr = channels.at(1);    Cb = channels.at(2);    Mat result;    result.create(Image.size(), CV_8UC1);//创建一个和原图像等大小的8bit无符号整形单通道灰度图片,图片名为result    /*遍历图像,将符合阈值范围的像素设置为255,其余为0*/    for (int j = 1; j < Y.rows ; j++)//处理所有的行    {        uchar* currentCr = Cr.ptr< uchar>(j);        uchar* currentCb = Cb.ptr< uchar>(j);        uchar* current = result.ptr< uchar>(j);        for (int i = 1; i < Y.cols ; i++)        {            if ((   currentCr[i] > 133) && (   currentCr[i] < 173) && (currentCb[i] > 77) && (currentCb[i] < 127))                current[i] = 255;//如果是133<=Cr<=173,77<=Cb<=127的全赋值为255,也就是白色            else                current[i] = 0;//如果不是133<=Cr<=173,77<=Cb<=127的全赋值为0,也就是黑色        }    }    imshow("检测后的图", result);    waitKey(0);    return 0;}