我嘗試比較2張圖像。爲此我使用2個PreentScreens一個接一個地進行(這是理想的)。當我比較這屏幕上象素比較:編程圖像比較
public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
{
CompareResult cr = CompareResult.ciCompareOk;
if (bmp1.Size != bmp2.Size)
{
cr = CompareResult.ciSizeMismatch;
}
else
{
for (int x = 0; x < bmp1.Width
&& cr == CompareResult.ciCompareOk; x++)
{
for (int y = 0; y < bmp1.Height
&& cr == CompareResult.ciCompareOk; y++)
{
if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
cr = CompareResult.ciPixelMismatch;
}
}
}
return cr;
}
我得到正確的結果,上面寫着 - 比較是相同的,但它需要大量的時間,當我試圖討論解決這個位圖,並比較其價值 - 我得到錯誤的結果。當我比較圖像與自身 - 一切正常。什麼可能是錯誤的?這裏是散列比較的代碼:
public enum CompareResult
{
ciCompareOk,
ciPixelMismatch,
ciSizeMismatch
};
public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
{
CompareResult cr = CompareResult.ciCompareOk;
//Test to see if we have the same size of image
if (bmp1.Size != bmp2.Size)
{
cr = CompareResult.ciSizeMismatch;
}
else
{
//Convert each image to a byte array
System.Drawing.ImageConverter ic =
new System.Drawing.ImageConverter();
byte[] btImage1 = new byte[1];
btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
byte[] btImage2 = new byte[1];
btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());
//Compute a hash for each image
SHA256Managed shaM = new SHA256Managed();
byte[] hash1 = shaM.ComputeHash(btImage1);
byte[] hash2 = shaM.ComputeHash(btImage2);
//Compare the hash values
for (int i = 0; i < hash1.Length && i < hash2.Length
&& cr == CompareResult.ciCompareOk; i++)
{
if (hash1[i] != hash2[i])
cr = CompareResult.ciPixelMismatch;
}
}
return cr;
}
這是不是「調試我的代碼」類問題?我建議你嘗試將它製作成SO格式,以便它對其他人有用。 – Kromster
我知道這不是代碼審查,但在C#中的枚舉前綴(如'ciCompareOk'中的'ci')是不方便的,因爲您必須始終首先引用枚舉。例如。 'CompareResult.CompareOk',所以沒有混淆的餘地。 – weston
兩個相同的散列碼並不意味着圖像是相等的。 –