C#用EmguCV实现获取2个图的相似度
相似度值越接近越0,表示越相似,末尾有程序效果截图。
static void Main(string[] args) { ImageComparator test = new ImageComparator(); test.setBaseImage(new Mat(@"D:/test22 - 副本.jpg")); test.setInputImage(new Mat(@"D:/test_jiaoyan_2.jpg")); Console.WriteLine(test.calculateDifference()); Console.ReadLine(); } public class ImageComparator { private Mat baseImg; private Mat inputImg; int nBins;//每个颜色通道使用的箱子数量 public ImageComparator() { nBins = 8;//默认8个箱子 } public void setBaseImage(Mat img) { baseImg = img; } public void setInputImage(Mat img) { inputImg = img; } /// <summary> /// 计算相似度 /// </summary> public double calculateDifference() { DenseHistogram[] histogramOfBaseImage = new DenseHistogram[3]; DenseHistogram[] histogramOfInputImage = new DenseHistogram[3]; for (int i = 0; i < 3; i++) { histogramOfBaseImage[i] = new DenseHistogram(nBins, new RangeF(0f, 255.1f)); histogramOfBaseImage[i].Calculate<byte>(new Image<Gray, byte>[] { baseImg.ToImage<Bgr, byte>().Split()[i] }, false, null); histogramOfInputImage[i] = new DenseHistogram(nBins, new RangeF(0f, 255.1f)); histogramOfInputImage[i].Calculate<byte>(new Image<Gray, byte>[] { inputImg.ToImage<Bgr, byte>().Split()[i] }, false, null); } Image<Bgr, float> histOfBaseImg = new Image<Bgr, float>(nBins, 1); Image<Bgr, float> histOfInputImg = new Image<Bgr, float>(nBins, 1); for (int i = 0; i < 3; i++) { for (int j = 0; j < nBins; j++) { histOfBaseImg.Data[0, j, i] = (float)histogramOfBaseImage[i].GetBinValues()[j]; histOfInputImg.Data[0, j, i] = (float)histogramOfInputImage[i].GetBinValues()[j]; } } return CvInvoke.CompareHist(histOfBaseImg, histOfInputImg, HistogramCompMethod.Bhattacharyya); } }