閱讀384 返回首頁    go 阿裏雲 go 技術社區[雲棲]


【膚色檢測(II)】Mat版

將之前寫的 (I) 中的內容改成了 Mat 版本:


//opencv2.0風格

#include "cv.h"
#include "highgui.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;
using namespace cv;


void whThresholdOtsu(Mat &src, Mat &dst)
{
	int height=src.rows;
	int width=src.cols;

	//histogram
	float histogram[256]={0};
	for(int i=0;i<height;i++) {
		unsigned char* p=(unsigned char*)src.data+src.step*i;
		for(int j=0;j<width;j++) {
			histogram[*p++]++;
		}
	}
	//normalize histogram
	int size=height*width;
	for(int i=0;i<256;i++) {
		histogram[i]=histogram[i]/size;
	}

	//average pixel value
	float avgValue=0;
	for(int i=0;i<256;i++) {
		avgValue+=i*histogram[i];
	}

	int threshold;	
	float maxVariance=0;
	float w=0,u=0;
	for(int i=0;i<256;i++) {
		w+=histogram[i];
		u+=i*histogram[i];

		float t=avgValue*w-u;
		float variance=t*t/(w*(1-w));
		if(variance>maxVariance) {
			maxVariance=variance;
			threshold=i;
		}
	}

	cv::threshold( src, dst, threshold, 255, THRESH_BINARY);
}

void cvSkinOtsu(Mat &src, Mat &dst)
{
	Mat ycrcb;
	Mat cr;
	cvtColor(src,ycrcb,CV_BGR2YCrCb);

	//show ycrcb, test
	//imshow("ycrcb",ycrcb);

	vector<Mat> mv;
	split(ycrcb,mv);

	whThresholdOtsu(mv[1],cr);
	imshow("out2",cr);

	//cvWaitKey(0);

	dst = cr.clone();
}


int main()
{
	Mat img = imread("mmr.jpg");

	//out用以保存輸出圖像
	Mat out;

	imshow("in",img);
	cvSkinOtsu(img,out);
	//imshow("out",out);

	cvWaitKey(0);

	return 0;
}




最後更新:2017-04-03 05:40:10

  上一篇:go 如何才能成為一名優秀的軟件測試人員
  下一篇:go 機房收費係統之思想性總結