如何将Image对象与C#.NET进行比较?

Lou*_*hys 13 .net c# testing image bitmap

我们可以Image用C#比较两个对象吗?例如,检查它们是否相等,甚至更好地检查它们的像素有多相似?

如果可能,怎么样?

Iga*_*nik 12

您可以使用一组名为TestApi的工具,这是一个开源库,可以帮助进行单元测试.其中一个API称为Visual Verification API,它完全符合您的需求 - 它可以比较两个图像并告诉您它们是否相等:

// 1. Capture the actual pixels from a given window
Snapshot actual = Snapshot.FromRectangle(new Rectangle(0, 0, 100, 100));

// 2. Load the reference/master data from a previously saved file
Snapshot expected = Snapshot.FromFile("Expected.png"));

// 3. Compare the actual image with the master image
//    This operation creates a difference image. Any regions which are identical in 
//    the actual and master images appear as black. Areas with significant 
//    differences are shown in other colors.
Snapshot difference = actual.CompareTo(expected);

// 4. Configure the snapshot verifier - It expects a black image with zero tolerances
SnapshotVerifier v = new SnapshotColorVerifier(Color.Black, new ColorDifference());

// 5. Evaluate the difference image
if (v.Verify(difference) == VerificationResult.Fail)
{
    // Log failure, and save the diff file for investigation
    actual.ToFile("Actual.png", ImageFormat.Png);
    difference.ToFile("Difference.png", ImageFormat.Png);
}
Run Code Online (Sandbox Code Playgroud)