图像对比在自动化中的使用。
在自动化过程中,有些地方是必须要用到图像进行对比的。比如拍照。拍一张照片,然后检查拍摄的照片和预览的照片是否一致。在手工测试时,非常的方便。但是程序该怎么做呢?
这时就需要进行图像相似度的对比。最简单的一个对比方法就是对比两张图片的像素,通过对比像素来看两张图片是否相似,但这种方法有个致命的弱点。准确度不高。如果两张照片的光线不一样。也会被认定为两张图片。不过此方法很简单。我先介绍此方法。在后续的文章里,在介绍照片对比的方法。
首先,我来说一下,最简单的图像对比的实现。大家都知道,图片是由一个一个的像素点构成。比如我们常见的手机分辨率1920*1080.则,手机屏幕上一共就有2073600个像素点。那么我们要进行图像对比时,最简单的一种方法就是,对比每个像素点是否一样。下面我们先看来这种简单的对比方法是怎么实现的。
此方法精度较低,误差较大,不适合用来对比照片等,有光线变化的图片,比较适合用于对比两张截图。照片的对比,在另一篇文章中介绍,使用汉明距离进行图像对比。
我们接下来来看看最简单的图像对比如何操作。在进行图像操作前,我们需要有一张基准图片,用来做参照。
基准图片可以在测试开始前截取,也可以存放到手机里,这里推荐是在开始测试前截图。
- 读取基准图片和对比图片。123// Get the original image and compare image.Bitmap mBitmap1 = BitmapFactory.decodeFile(originalImagePath);Bitmap mBitmap2 = BitmapFactory.decodeFile(compareImagePath);
这里使用的是Bitmap的类,来从文件中创建一个bitmap对象,便于后续处理。
获取图片的宽高
123//get the image width and height.int width = mBitmap2.getWidth();int height = mBitmap2.getHeight();计算出图片的总像素
1double totalPixels = height * width;统计两种照片的不同像素信息
12345678for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {// find all not same pixels.if (mBitmap2.getPixel(x, y) != mBitmap1.getPixel(x, y)) {numDiffPixels++;}}}
说明:
外循环以图片的高为限制,内循环以图片的宽为限制,循环比较像素点的信息,把所有不同的像素点存放起来。得到不同像素信息。
计算相似度
123456// get the all different pixel of image..double diffPercent = numDiffPixels / totalPixels;double result = 1.0 - diffPercent;System.out.println("The similarity Percent is:" + result);return similarityPercent <= result;完成代码如下:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/*** If you want compare two image is same or not,you can use this method.* I recommend use method to compare two screen short.* if you want to compare two photo,please use isSameAs(originalImagePath,compareImagePath).** @param originalImagePath The original image path.* @param compareImagePath the compare image path.* @param similarityPercent if the two image is same, Percent should be set to 100%* @return is two image is same,the result is true.*/public static boolean isSameAs(String originalImagePath,String compareImagePath, double similarityPercent) {try {// Get the original image and compare image..Bitmap mBitmap1 = BitmapFactory.decodeFile(originalImagePath);Bitmap mBitmap2 = BitmapFactory.decodeFile(compareImagePath);//get the image width and height.int width = mBitmap2.getWidth();int height = mBitmap2.getHeight();// set the pixels number.int numDiffPixels = 0;// compare all pixels is same or not.for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {// find all not same pixels.if (mBitmap2.getPixel(x, y) != mBitmap1.getPixel(x, y)) {numDiffPixels++;}}}// get the all pixel of the picture.double totalPixels = height * width;// get the all different pixel of image..double diffPercent = numDiffPixels / totalPixels;//double result = 1.0 - diffPercent;System.out.println("The similarity Percent is:" + result);return similarityPercent <= result;} catch (Exception e) {e.printStackTrace();}return false;}