# encoding: utf-8 ''' 用于两张图片比对检测 ''' import cv2 as cv import numpy as np import random # from matplotlib import pyplot as plt GRAY_LEVEL = 255 class DoubleImage(): def __init__(self): pass #裁剪图片 def cutImage(self, img_addr): img = cv.imread(img_addr) img_arr = np.array(img) hight = img_arr.shape[0] wight = img_arr.shape[1] dest_img = img_arr[hight-280:hight-180,wight-280:wight-180] return dest_img ''' 比较两张图片,如果根据threshold设定的容错值,有1%的点超过范围,则图片不一致。 :param picPath1:第一个参数为为标准图地址, :param picPath2:第二个参数为测试图地址 :param threshold: RGB颜色偏差容错范围 ''' def cmpPicTotal(self, picPath1, picPath2, threshold=20, expDotRate=0.01): srcImg1 = cv.imread(picPath1) srcImg2 = cv.imread(picPath2) return self.cmpImgTotal(srcImg1, srcImg2, threshold, expDotRate) ''' 比较两张图片,如果根据threshold设定的容错值,有1%的点超过范围,则图片不一致。 :param picPath1:第一个参数为为标准图对象, :param picPath2:第二个参数为测试图对象 :param threshold: RGB颜色偏差容错范围 ''' def cmpImgTotal(self, srcImg1, srcImg2, threshold=20, expDotRate=0.01): shape = srcImg2.shape dstImg = srcImg1 - srcImg2 cv.imwrite("D:/dstImg.png", dstImg) bArr = dstImg[:,:,0].ravel() gArr = dstImg[:,:,1].ravel() rArr = dstImg[:,:,2].ravel() dotSum = shape[0]*shape[1]+0.0 bCount = np.where((bArr>threshold)&(bArr<=255))[0].__len__() gCount = np.where((gArr>threshold)&(gArr<=255))[0].__len__() rCount = np.where((rArr>threshold)&(rArr<=255))[0].__len__() print "cmpImgTotal BGR点异常个数比例:", bCount/dotSum,gCount/dotSum,rCount/dotSum if bCount/dotSum>expDotRate or gCount/dotSum > expDotRate or rCount/dotSum>expDotRate: return False else: return True ''' 缺少衡量等级数字量化 ''' def cmpORB(self, im1, im2): orb = cv.ORB_create() kp = orb.detect(im1, None) kp, des1 = orb.compute(im1,kp) print "des1:",des1.__len__() # draw only keypoints location,not size and orientation # img1 = cv.drawKeypoints(im1, kp, None, color=(0, 255, 0), flags=0) # plt.imshow(img1), plt.show() orb = cv.ORB_create() kp2 = orb.detect(im2, None) kp2, des2 = orb.compute(im2, kp2) print "des2:",des2.__len__() # draw only keypoints location,not size and orientation # img2 = cv.drawKeypoints(im2, kp, None, color=(0, 255, 0), flags=0) # plt.imshow(img2), plt.show() if __name__ == '__main__': dImg = DoubleImage() # dImg.cmpPicTotal('flower.jpg', 'flower.jpg') im1 = cv.imread('std.jpg') im2 = cv.imread('test.jpg') # psnr = dImg.psnr(im1, im2) # print "im1,im2 psnr:", psnr # dImg.cmpHist(im1 , im2) dImg.cmpORB(im1,im2)