Python笔记-使⽤SSIM两张图不同及使⽤Opencv显⽰运⾏截图如下:
这⾥有⼏点要注意的:
①对⽐两张图⽚的函数SSIM具体是structural_similarity:
Ⅰ:第⼀个参数和第⼆个参数是要对⽐的两张图⽚;
Ⅱ:参数中有个full,默认为True,如果为True会把两张图的相似部分返回,如果为False就不返回了;
Ⅳ:返回值full为False的时候有2个,⼀个是mssim浮点型的相似度,1代表2张图⼀模⼀样。0代表完全不⼀样,grad返回两张图⽚不同的地⽅类型为ndarray;
②SSIM返回的ndarray⾥⾯的值为[0, 1]的float型,⽽OpenCV的[0, 255]为uint8型,可以通过这样的⽅式转换:
Ⅰ:diff = (diff * 255).astype("uint8")
③cv2.threshold函数,设置⼀个阈值和⼀个颜⾊,将传⼊的图⽚没有达到这个阈值的,转换为这个颜⾊。
源码如下:
ics import structural_similarity
import cv2
import numpy as np
if __name__ == '__main__':
before = cv2.imread('./pic/demo1.png')
after = cv2.imread('./pic/demo2.png')
# Convert images to grayscale
before_gray = cv2.cvtColor(before, cv2.COLOR_BGR2GRAY)
after_gray = cv2.cvtColor(after, cv2.COLOR_BGR2GRAY)
# Compute SSIM between two images
(score, diff) = structural_similarity(before_gray, after_gray, full=True)rectangle函数opencv
print("Image similarity", score)
# The diff image contains the actual image differences between the two images
# and is represented as a floating point data type in the range [0,1]
# so we must convert the array to 8-bit unsigned integers in the range
# [0,255] before we can use it with OpenCV
diff = (diff * 255).astype("uint8")
# Threshold the difference image, followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
contours = cv2.py(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1]
mask = np.zeros(before.shape, dtype='uint8')
filled_after = py()
for c in contours:
area = urArea(c)
if area > 40:
x, y, w, h = cv2.boundingRect(c)
cv2.drawContours(mask, [c], 0, (0, 255, 0), -1)
cv2.drawContours(filled_after, [c], 0, (0, 255, 0), -1)
cv2.imshow('before', before)
cv2.imshow('after', after)
cv2.imshow('diff', diff)
cv2.imshow('mask', mask)
cv2.imshow('filled after', filled_after)
cv2.waitKey(0)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论