利用OpenCV和Python实现查找图片差异
使用OpenCV和Python查找图片差异
flyfish
方法1均方误差的算法(MeanSquaredError,MSE)
下面的一些表达与《TensorFlow-协方差矩阵》式子表达式一样的
拟合误差平方和(sumofsquarederrors)
residualsumofsquares(RSS),alsoknownasthesumofsquaredresiduals(SSR)orthesumofsquarederrorsofprediction(SSE),
alsoknownas就我们所说的
RSS,SSR,SSE表达的是一个意思
defmse(imageA,imageB): #the'MeanSquaredError'betweenthetwoimagesisthe #sumofthesquareddifferencebetweenthetwoimages; #NOTE:thetwoimagesmusthavethesamedimension err=np.sum((imageA.astype("float")-imageB.astype("float"))**2) err/=float(imageA.shape[0]*imageA.shape[1]) #returntheMSE,thelowertheerror,themore"similar" #thetwoimagesare returnerr
方法2SSIM
structuralsimilarityindexmeasurement(SSIM)system
一种衡量两幅图像结构相似度的新指标,其值越大越好,最大为1。
新建一个Python文件,命名为image_diff.py
原文
ImageDifferencewithOpenCVandPython
原理
根据参数读取两张图片并转换为灰度:
使用SSIM计算两个图像之间的差异,这种方法已经在scikit-image库中实现
在两个图像之间的不同部分绘制矩形边界框。
代码如下已编译通过
fromskimage.measureimportcompare_ssim #~importskimageasssim importargparse importimutils importcv2 #constructtheargumentparseandparsethearguments ap=argparse.ArgumentParser() ap.add_argument("-f","--first",required=True, help="firstinputimage") ap.add_argument("-s","--second",required=True, help="second") args=vars(ap.parse_args()) #loadthetwoinputimages imageA=cv2.imread(args["first"]) imageB=cv2.imread(args["second"]) ''' imageA=cv2.imread("E:\\1.png") imageB=cv2.imread("E:\\2.png") ''' #converttheimagestograyscale grayA=cv2.cvtColor(imageA,cv2.COLOR_BGR2GRAY) grayB=cv2.cvtColor(imageB,cv2.COLOR_BGR2GRAY) #computetheStructuralSimilarityIndex(SSIM)betweenthetwo #images,ensuringthatthedifferenceimageisreturned #structuralsimilarityindexmeasurement(SSIM)system一种衡量两幅图像结构相似度的新指标,其值越大越好,最大为1。 (score,diff)=compare_ssim(grayA,grayB,full=True) diff=(diff*255).astype("uint8") print("SSIM:{}".format(score)) #thresholdthedifferenceimage,followedbyfindingcontoursto #obtaintheregionsofthetwoinputimagesthatdiffer thresh=cv2.threshold(diff,0,255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)[1] cnts=cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts=cnts[0]ifimutils.is_cv2()elsecnts[1] #loopoverthecontours forcincnts: #computetheboundingboxofthecontourandthendrawthe #boundingboxonbothinputimagestorepresentwherethetwo #imagesdiffer (x,y,w,h)=cv2.boundingRect(c) cv2.rectangle(imageA,(x,y),(x+w,y+h),(0,0,255),2) cv2.rectangle(imageB,(x,y),(x+w,y+h),(0,0,255),2) #showtheoutputimages cv2.imshow("Original",imageA) cv2.imshow("Modified",imageB) cv2.imshow("Diff",diff) cv2.imshow("Thresh",thresh) cv2.waitKey(0)
使用方法
pythonimage_diff.py–firstoriginal.png–secondimages/modified.png
如果不想使用参数将参数代码部分直接变成
imageA=cv2.imread(“E:\1.png”) imageB=cv2.imread(“E:\2.png”)
以上这篇利用OpenCV和Python实现查找图片差异就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。