基于opencv的肤色检测

来源:互联网 发布:如何卸载网络打印机 编辑:程序博客网 时间:2024/06/10 19:21
不说废话,直接上代码
#include <opencv2/core/core.hpp>  #include <opencv2/highgui/highgui.hpp>  #include <opencv2/contrib/contrib.hpp>  #include <opencv2/imgproc/imgproc.hpp>  #include <iostream>  #include <vector>     int main(){cv::Mat srcImage, resultMat;srcImage = cv::imread("hand1.jpg");if (srcImage.empty())return -1;// 构建椭圆模型   cv::Mat skinMat = cv::Mat::zeros(cv::Size(256, 256), CV_8UC1);ellipse(skinMat, cv::Point(113, 155.6), cv::Size(23.4, 15.2),43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);// 结构元素定义cv::Mat struElmen = getStructuringElement(cv::MORPH_RECT,cv::Size(3, 3), cv::Point(-1, -1));cv::Mat YcrcbMat;cv::Mat tempMat = cv::Mat::zeros(srcImage.size(), CV_8UC1);// 颜色空间转换YCrCbcvtColor(srcImage, YcrcbMat, CV_BGR2YCrCb);// 椭圆皮肤模型检测for (int i = 0; i < srcImage.rows; i++){uchar* p = (uchar*)tempMat.ptr<uchar>(i);cv::Vec3b* ycrcb = (cv::Vec3b*)YcrcbMat.ptr<cv::Vec3b>(i);for (int j = 0; j < srcImage.cols; j++){// 颜色判断if (skinMat.at<uchar>(ycrcb[j][1], ycrcb[j][2]) > 0)p[j] = 255;}}// 形态学闭操作     morphologyEx(tempMat, tempMat, cv::MORPH_CLOSE, struElmen);// 定义轮廓参数std::vector< std::vector<cv::Point> > contours;std::vector< std::vector<cv::Point> > resContours;std::vector< cv::Vec4i > hierarchy;// 连通域查找findContours(tempMat, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);// 筛选伪轮廓   for (size_t i = 0; i < contours.size(); i++){if (fabs(contourArea(cv::Mat(contours[i]))) > 1000)resContours.push_back(contours[i]);}tempMat.setTo(0);// 绘制轮廓drawContours(tempMat, resContours, -1, cv::Scalar(255, 0, 0), CV_FILLED);srcImage.copyTo(resultMat, tempMat);imshow("srcImage", srcImage);imshow("resultMat", resultMat);cv::waitKey(0);return 0;}
执行结果:原图


效果图


csdn opencv http://lib.csdn.net/base/opencv

1 0