private void button43_Click(object sender, EventArgs e)
{
Mat baseMat = new Mat();
Mat detectedMat = new Mat();
if (chapter1OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
baseMat = CvInvoke.Imread(chapter1OFD.FileName, LoadImageType.AnyColor | LoadImageType.AnyColor);
//获取基准图像,该图像用来获得狒狒脸部ROI
if (baseMat.IsEmpty | baseMat.NumberOfChannels != 3)
return;
var rect = new System.Drawing.Rectangle(113, 252, 35, 40);
var tempImg = baseMat.Clone();
CvInvoke.NamedWindow("baseImage", NamedWindowType.KeepRatio);
CvInvoke.Rectangle(tempImg, rect, new MCvScalar(0, 0, 255), 2);
CvInvoke.Imshow("baseImage", tempImg);
//显示基准图像,并标出ROI区域
var imgROI = new Mat(baseMat, rect);
//狒狒脸部ROI
//屏蔽饱和度过低的像素,得到掩码mask
int minSat = 65;
var hsvROI = new Mat();
CvInvoke.CvtColor(imgROI, hsvROI, ColorConversion.Bgr2Hsv);
var hsvROIImg = hsvROI.ToImage<Hsv, byte>();
var mask = new Mat();
CvInvoke.Threshold(hsvROIImg.Split()[1], mask, minSat, 255, ThresholdType.Binary);
//得到ROI色调直方图,mask中的像素没有参与计算
DenseHistogram hist = new DenseHistogram(181, new RangeF(0f, 180.1f));
hist.Calculate<byte>(new Image<Gray, byte>[] { hsvROIImg.Split()[0] }, false, mask.ToImage<Gray, byte>());
//获取将要检测的图像,并对HSV图像中的色调图像反投影
if (chapter1OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
detectedMat = CvInvoke.Imread(chapter1OFD.FileName, LoadImageType.AnyColor | LoadImageType.AnyColor);
//获取图像
if (detectedMat.IsEmpty | detectedMat.NumberOfChannels != 3)
return;
var hsvMat = new Mat();
CvInvoke.CvtColor(detectedMat, hsvMat, ColorConversion.Bgr2Hsv);
//获取HSV数据
var resultImg = hist.BackProject<byte>(new Image<Gray, byte>[] { hsvMat.ToImage<Hsv, byte>().Split()[0] });
var criteria = new MCvTermCriteria(1000, 0.01);
CvInvoke.MeanShift(resultImg, ref rect, criteria);
//均值偏移,计算得到脸部区域
tempImg = detectedMat.Clone();
CvInvoke.Rectangle(tempImg, rect, new MCvScalar(255, 0, 0), 2);
CvInvoke.NamedWindow("detectedImage", NamedWindowType.KeepRatio);
CvInvoke.Imshow("detectedImage", tempImg);
}