opencv图像识别技术在自动化测试中的应用

在自动化测试中,基于xpath、js选择器、css选择器进行元素定位及判定的技术已经比较成熟。在实际应用中,无论是web端还是移动端,仍有很多时候需要根据页面内容、页面中的图像进行定位及判定,这里介绍一下基于opencv的图像识别技术在自动化测试中的应用。

这里我们使用selenium驱动测试,使用opencv进行页面元素判定。

OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库,可以运行在Linux、Windows和Mac OS操作系统上。它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法。

0.基本步骤

在自动化测试中,我们预先对目标图像进行截图,使用selenium驱动页面访问,使用xpath预先验证指定元素是否存在,之后使用opencv的模板匹配对元素的内容进行验证。

在示例中,我们使用百度搜索opencv,验证搜索结果中是否包含百度百科的词条,以及百度百科词条中opencv的logo是否存在。

1.测试环境:

Firefox  v42.0

Python v2.7.10

Opencv v2.4.8

Numpy v1.8.1

Selenium v2.47.1

2.准备目标图像

使用baidu搜索opencv,并对我们需要验证的图像进行截图。

3.使用selenium打开baidu进行搜索

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.baidu.com") # Load page
assert "百度" in browser.title
elem = browser.find_element_by_id("kw") # Find the query box
elem.send_keys("opencv" + Keys.RETURN)
time.sleep(1) # Let the page load, will be added to the API

4.使用selenium验证搜索结果中是否含有百度百科词条,这里我们使用xpath进行验证

try:
    browser.find_element_by_xpath("//h3/a[contains(text(),'_')]") #find baike in result page
    browser.save_screenshot('D://source.jpg') #save page 
except NoSuchElementException:
assert 0, "can't find opencv element"

5.使用opencv验证图像是否存在

复制代码
sourcename = "D:/source.jpg"
source = cv.LoadImage(sourcename)
templatename="D:/template2.jpg"
template=cv.LoadImage(templatename)

W,H=cv.GetSize(source)
w,h=cv.GetSize(template)
width=W-w+1 
height=H-h+1
result=cv.CreateImage((width,height),32,1)  #result是一个矩阵,用于存储模板与源图像每一帧相比较后的相似值

cv.MatchTemplate(source,template, result,cv.CV_TM_SQDIFF) #从矩阵中找到相似值最小的点,从而定位出模板位置
(min_x,max_y,minloc,maxloc)=cv.MinMaxLoc(result)
(x,y)=minloc
print min_x,max_y,minloc,maxloc
assert (min_x<10000000), "can't find opencv image"
复制代码

6.查看验证结果

在编写脚本过程中,由于实际的图像处理偏差,min_x的最大值需要根据具体图像进行不同的调整,校验时,可以将图像识别的结果进行输出,以便于查看。

cv.Rectangle(source,(int(x),int(y)),(int(x)+w,int(y)+h),(0,0,255),2,0) #use red rectangle to notify the target
cv.ShowImage("result", source)
cv.WaitKey()

图像识别结果:

 

参考资料:

Opencv模板匹配:http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html

 

完整代码请参考:

https://github.com/buaawp/automationT/blob/master/demo_opencv.py

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓