使用Python查找轮廓生成看图找茬的框图

Published: Tags: PYTHON
#!/bin/python
# -*- coding: utf-8 -*-
# picdiff_rect_marker.py by jtwo

import sys, json, cv2, numpy
from PIL import Image, ImageChops

rs_name = sys.argv[1]

layer   = Image.open(rs_name+'/layer.jpg')
layer_1 = Image.open(rs_name+'/layer_1.jpg')

diffImg = ImageChops.difference(layer, layer_1)

diffImg = ImageChops.add(diffImg, diffImg, scale=1, offset=-30) #处理噪点
#diffImg.save(rs_name+'/marker_diff.jpg')

diffImgColor = cv2.cvtColor(numpy.array(diffImg), cv2.COLOR_RGB2BGR) #PIL转CV
diffImgGray = cv2.cvtColor(diffImgColor, cv2.COLOR_BGR2GRAY)
#cv2.imwrite(rs_name+'/marker_gray.jpg', diffImgGray)

thImage = cv2.threshold(diffImgGray, 0, 255, cv2.THRESH_BINARY)[1]
diffRect = cv2.findContours(thImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

# diffArea = 0 #差异面积总值
# for i in range(len(diffRect)):
#     diffArea += cv2.contourArea(diffRect[i])
# diffArea = (diffArea / len(diffRect)) * 1 #差异面积平均比例

maxFew = [0,0,0,0,0,0] #记录最大差异面积的几个矩形(5+N)
for i in range(len(diffRect)):
    currentArea = cv2.contourArea(diffRect[i])
    if currentArea>maxFew[0] and currentArea not in maxFew:
        maxFew[0] = currentArea #替换最小面积,最小的是[0]
        maxFew.sort() #差异面积排序,必须最后排序一次
        #print cv2.boundingRect(diffRect[i]), int(currentArea)

diffCoord = json.loads('[{"x":0,"y":0,"w":900,"h":563}]')
for i in range(len(diffRect)):
    x, y, w, h = cv2.boundingRect(diffRect[i])
    currentArea = cv2.contourArea(diffRect[i])
    if currentArea>=maxFew[0] and currentArea>=70: #大于差异面积阈值
        if currentArea < 2000: #差异面积较小,手机不太方便点击
            x -= 15; y -= 15; w += 30; h += 30 #点击误差补偿
        diffCoord.append( {"x":x, "y":y, "w":w, "h":h} )
        markImg = cv2.rectangle(diffImgColor, (x,y), (x+w,y+h), (255,255,255), 1)
        #print {"x":x,"y":y,"w":w,"h":h}, int(currentArea), int(maxFew[0])

with open(rs_name+'/level.json', 'w') as lj:
    json.dump(diffCoord, lj, separators=(',',':'))

cv2.imwrite(rs_name+'/marker.jpg', markImg)

# time ls |grep picdiff_asset_ |while read pda; do echo $pda; python picdiff_rect_marker.py $pda; done

调试了一天,特此记录,参考资料: 画轮廓的新人 OpenCV形状识别 OpenCV中几何形状识别与测量 OpenCV-Python教程(轮廓检测) OpenCV任意形状目标检测,并绘制框图 Python+OpenCV颜色和形状检测