Fuzzy screenshot comparison with Selenium

前端 未结 4 2097
我在风中等你
我在风中等你 2021-02-05 20:22

I\'m using Selenium to automate webpage functional testing. It\'s important for us to do a pixel-by-pixel comparison when we roll out new code, so we\'re using Selenium to take

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 20:50

    Use an image format that does not create artifacts (like BMP or PNG) then you can do a per-pixel comparison. I think you can check each pixel with a common Euclidean Distance. To improve performance a little, do not calculate the square root but check the squares of the distances

    // Maximum color distance allowed to define pixel consistency.
    const float maxDistanceAllowed = 5.0;
    
    // Square of the distance, used in calculations.
    float maxD = maxDistanceAllowed * maxDistanceAllowed;
    
    public bool isPixelConsistent(Color pixel1, Color pixel2)
    {
        // Euclidean distance in 3-dimensions.
        float distanceSquared = (pixel1.R - pixel2.R)*(pixel1.R - pixel2.R) + (pixel1.G - pixel2.G)*(pixel1.G - pixel2.G) + (pixel1.B - pixel2.B)*(pixel1.B - pixel2.B);
    
        // If the actual distance is less than the max allowed, the pixel is
        // consistent and the method returns TRUE
        return distanceSquared <= maxD;
    }
    

    Didn't test the C# code, but it should give you the idea. Give some tries and adjust the maxDistanceAllowed to your needs.

提交回复
热议问题