首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

圖像相似度演算法的 C# 實作與測評(二)

     編輯:關於C語言

程式碼實作

步驟 1,將圖像轉換成相同大小,暫且轉成 256x256。

public Bitmap Resize(string imageFile, string newImageFile)
{
    img = Image.FromFile(imageFile);
    Bitmap imgOutput = new Bitmap(img, 256, 256);
    imgOutput.Save(newImageFile, System.Drawing.Imaging.ImageFormat.Jpeg);
    imgOutput.Dispose();
    return (Bitmap)Image.FromFile(newImageFile);
}

這部分很好懂,imageFile 為原始圖片完整路徑,newImageFile 為縮放後 256x256 圖片的路徑,為了賽後能看到轉換出來的圖片長什麼樣,所以存到本地,導致上面略顯醜陋的程式碼。

步驟 2,計算圖像的直方圖

public int[] GetHisogram(Bitmap img)
{
    BitmapData data = img.LockBits(new System.Drawing.Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    int[] histogram = new int[256];
    unsafe
    {
        byte* ptr = (byte*)data.Scan0;
        int remain = data.Stride - data.Width * 3;
        for (int i = 0; i < histogram.Length; i++) histogram[i] = 0;
        for (int i = 0; i < data.Height; i++)
        {
            for (int j = 0; j < data.Width; j++)
            {
                int mean = ptr[0] + ptr[1] + ptr[2];
                mean /= 3;
                histogram[mean]++;
                ptr += 3;
            }
            ptr += remain;
        }
    }
    img.UnlockBits(data);
    return histogram;
}

這段就是驚天地泣鬼神的灰度直方圖計算方法,裡面的彎彎繞還是留給諸位自己去摻和。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved