萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

C# 高效能比較兩張圖片是否完全相同 (像素級比對)

需快速判斷兩張 Bitmap 是否像素級完全一致,最佳做法是鎖定記憶體 (LockBits) 直接比對原始位元組陣列,避免 GetPixel 極慢的逐像素呼叫。

高效能比對實作

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

public static bool AreImagesIdentical(Bitmap img1, Bitmap img2)
{
    // 1. 尺寸快速檢查
    if (img1.Width != img2.Width || img1.Height != img2.Height)
        return false;

    // 2. 鎖定記憶體 (ReadOnly, 24bpp RGB 格式統一)
    var rect = new Rectangle(0, 0, img1.Width, img1.Height);
    var bmpData1 = img1.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    var bmpData2 = img2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

    try
    {
        int stride = bmpData1.Stride; // 每行位元組數 (含填充)
        int height = img1.Height;
        int widthBytes = img1.Width * 3; // 實際像素資料寬度 (24bpp = 3 bytes)

        // 3. 逐行比對 (利用 Stride 處理記憶體對齊填充)
        unsafe
        {
            byte* ptr1 = (byte*)bmpData1.Scan0;
            byte* ptr2 = (byte*)bmpData2.Scan0;

            for (int y = 0; y < height; y++)
            {
                // 只比對有效像素寬度,忽略行尾填充位元組
                for (int x = 0; x < widthBytes; x++)
                {
                    if (ptr1[x] != ptr2[x]) return false;
                }
                // 移至下一行 (跳過 stride)
                ptr1 += stride;
                ptr2 += stride;
            }
        }
        return true;
    }
    finally
    {
        // 4. 必須解鎖
        img1.UnlockBits(bmpData1);
        img2.UnlockBits(bmpData2);
    }
}

關鍵優化點解析

技術說明
LockBits將影像資料鎖定在記憶體固定位址,取得指標直接存取,避免 GetPixel 邊界檢查與座標轉換開銷
Format24bppRgb統一像素格式為 24-bit RGB (3 bytes/pixel),簡化比對邏輯,避免 32bpp Alpha 通道干擾
Stride 處理每行記憶體可能因 4-byte 對齊有填充位元組,必須用 Stride 而非 Width*3 計算行偏移
Unsafe 指標編譯需勾選「允許不安全代碼」,比 Marshal.Copy 到 byte[] 再比對更快 (省去複製記憶體)
早期退出發現第一個不同像素立即返回 false

安全版本 (不使用 unsafe)

public static bool AreImagesIdenticalSafe(Bitmap img1, Bitmap img2)
{
    if (img1.Width != img2.Width || img1.Height != img2.Height) return false;

    var rect = new Rectangle(0, 0, img1.Width, img1.Height);
    var bd1 = img1.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    var bd2 = img2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

    try
    {
        int stride = bd1.Stride;
        int height = img1.Height;
        int widthBytes = img1.Width * 3;
        byte[] bytes1 = new byte[stride * height];
        byte[] bytes2 = new byte[stride * height];
        
        Marshal.Copy(bd1.Scan0, bytes1, 0, bytes1.Length);
        Marshal.Copy(bd2.Scan0, bytes2, 0, bytes2.Length);

        for (int y = 0; y < height; y++)
        {
            int offset = y * stride;
            for (int x = 0; x < widthBytes; x++)
                if (bytes1[offset + x] != bytes2[offset + x]) return false;
        }
        return true;
    }
    finally
    {
        img1.UnlockBits(bd1);
        img2.UnlockBits(bd2);
    }
}

進階:感知雜訊比較 (Perceptual Hash / SSIM)

若需「視覺上相似」而非「位元完全相同」(如壓縮伪影、微小色差),請使用:

  • pHash (Perceptual Hash): 縮放→灰階→DCT→取低頻係數→生成 64-bit 指紋,漢明距離判斷相似度。
  • SSIM (Structural Similarity Index): 結構相似性指標,更符合人眼感知。
  • 推薦庫:ImageSharp、ImageMagick.NET、PerceptualHash。

效能基準參考 (1920x1080 圖片)

  • GetPixel 迴圈:~2,500 ms
  • LockBits + Marshal.Copy + 陣列比對:~15 ms
  • LockBits + unsafe 指標逐行比對:~5 ms (最快)

結論:LockBits + unsafe 指標逐行比對 是 C# 判斷圖片位元級相同的最高效能做法,記得編啟專案屬性 → Build → Allow unsafe code。

copyright © 萬盛學電腦網 all rights reserved