基于openCV和python的skimage查找并标记两张图片的不同
前言
UI测试过程中,会涉及大量的界面图片的样式、背景、颜色等检查,使用肉眼检查效率低,并且容易遗漏细微的差异。以下记录利用opencv的cv2结合skimage实现简单实现图像对比的功能的实现步骤。
文章目录
前言
一、openCV和skimage简介
二、环境准备
1.安装opencv-python
三、代码实现
1.导入图像处理库
2.读取图片
3.调整对比的两张图片尺寸一样
4.图片转灰度图
5.使用structural_similarity对比获取图像相似度和不同
6.圈出不同并标记序号
四、效果图
一、openCV和skimage简介
OpenCV(open source computer vision library)是一个基于BSD许可(开源)发行的跨平台计算机视觉库,可以运行在Linux、Windows、Android和Mac OS操作系统上。
它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法。
Scikit-Image(skimage)是一个用于图像处理的Python库,提供了丰富的算法和工具,用于图像滤波、形态学处理、颜色转换、边缘检测、图像分割等。它的设计理念是简洁、易用和功能强大,适合快速开发和实验。
二、环境准备
1.安装opencv-python
pip install opencv-python
如果安装失败,可以-i加上镜像地址安装
2.安装scikit-image
pip install scikit-image
三、代码实现
1.导入图像处理库
from skimage.metrics import structural_similarity as compare_ssim
import imutils
import cv2
import numpy as np
2.读取图片
image = "C:/Users/ts/Desktop/img/screenshot.png"
imageCompare = "C:/Users/ts/Desktop/img/screenshot1.png"
image= cv2.imdecode(np.fromfile(image, dtype=np.uint8), -1)
image_compare= cv2.imdecode(np.fromfile(image_compare, dtype=np.uint8), -1)
3.调整对比的两张图片尺寸一样
h1, w1,c1 = image.shape
h2, w2,c2= imageCompare.shape
image_compare = cv2.resize(image_compare ,dsize=(w1,h1))
4.图片转灰度图
gray_image= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
gray_image_ompare = cv2.cvtColor(image_compare ,cv2.COLOR_BGR2GRAY)
5.使用structural_similarity对比获取图像相似度和不同
(score,diff) = compare_ssim(gray_image,gray_image_ompare ,full = True)
diff = (diff *255).astype("uint8")
retval,thresh = cv2.threshold(diff,200,255,cv2.THRESH_BINARY_INV)
#参数thresh:阈值,用于确定像素是否应该被视为前景或背景,调测下来200比较合适
cnts=cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[1] if imutils.is_cv3() else cnts[0]
loacation_list =[]
for c in cnts:
(x,y,w,h) = cv2.boundingRect(c)
loacation_list.append((x,y,x+w,y+h))
6.圈出不同并标记序号
for index,item in enumerate(loacation_list):
#圈出不同
x,y,x1,y1 = item
cv2.rectangle(imageA,(x,y),(x1,y1),(0,0,255),2)
cv2.rectangle(imageB,(x,y),(x1,y1),(0,0,255),2)
#不同处添加序号
imageA = cv2.putText(imageA,str(index+1), (x,y+24), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255))
四、效果图
对比图1
对比图2
对比结果图
作者:甜果酱C