如何利用Python3和OpenCV对比两张图片的不同,提取差异性

如何利用Python3和OpenCV对比两张图片的不同,提取差异性

导言:通过机器视觉来计算两个图片之间的差异性,可以快速有效辨别文件、图片是否被篡改,也能帮助用户轻松识别钓鱼网站,确保财产安全。

一、所需模块

pip install --upgrade scikit-image
pip install --upgrade imutils

二、Python实现

# import the necessary packages
from skimage.measure import compare_ssim
import argparse
import imutils
import cv2
 
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--first", required=True,
	help="first input image")
ap.add_argument("-s", "--second", required=True,
	help="second")
args = vars(ap.parse_args())

# load the two input images
imageA = cv2.imread(args["first"])
imageB = cv2.imread(args["second"])
 
# convert the images to grayscale
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

# compute the Structural Similarity Index (SSIM) between the two
# images, ensuring that the difference image is returned
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

# 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]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the contours
for c in cnts:
	# compute the bounding box of the contour and then draw the
	# bounding box on both input images to represent where the two
	# images differ
	(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)
 
# show the output images
cv2.imshow("Original", imageA)
cv2.imshow("Modified", imageB)
cv2.imshow("Diff", diff)
cv2.imshow("Thresh", thresh)
cv2.waitKey(0)

三、运行代码

如下图所示,cmd打开电脑终端,输入运行参数(即图片存储路径),Enter键运行。具体方法见上一篇博文:如何使用Argparse模块

程序运行方法

四、运行结果

运行结果

后记:需要对比的两张图片必须尺寸大小一致,即像素矩阵一致,否则无法对比提取差异性。有问题欢迎留言!

  • 9
    点赞
  • 89
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
以下是读取两个文件夹中图像并进行性质差异分析的Python代码,使用了OpenCV库和scikit-image库。 ```python import cv2 from skimage import feature import numpy as np import os # 定义函数,提取图像的颜色、纹理和形状特征 def extract_features(image): # 提取颜色特征,计算每个通道的平均值和标准差 mean, std = cv2.meanStdDev(image) mean = np.transpose(mean) std = np.transpose(std) color_features = np.concatenate((mean, std), axis=1).flatten() # 提取纹理特征,计算LBP特征直方图 lbp = feature.local_binary_pattern(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), 8, 1) (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, 11), range=(0, 10)) hist = hist.astype("float") hist /= (hist.sum() + 1e-7) texture_features = hist.flatten() # 提取形状特征,计算Hu矩 moments = cv2.moments(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) hu_moments = cv2.HuMoments(moments).flatten() shape_features = hu_moments return np.concatenate((color_features, texture_features, shape_features)) # 定义函数,归一化图像 def normalize_image(image): return cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX) # 定义函数,读取文件夹中的图像并提取特征 def read_images(folder): features = [] for filename in os.listdir(folder): if filename.endswith(".jpg"): image_path = os.path.join(folder, filename) image = cv2.imread(image_path) image = normalize_image(image) feature_vector = extract_features(image) features.append(feature_vector) return np.array(features) # 读取两个文件夹中的图像并提取特征 us2_features = read_images("D:/zzz/us2") na2_features = read_images("D:/zzz/na2") # 计算两种图像的特征差异性 color_diff = np.abs(np.mean(us2_features[:, :6], axis=0) - np.mean(na2_features[:, :6], axis=0)) texture_diff = np.abs(np.mean(us2_features[:, 6:16], axis=0) - np.mean(na2_features[:, 6:16], axis=0)) shape_diff = np.abs(np.mean(us2_features[:, 16:], axis=0) - np.mean(na2_features[:, 16:], axis=0)) # 输出特征差异性 print("Color difference:", color_diff) print("Texture difference:", texture_diff) print("Shape difference:", shape_diff) ``` 该代码首先定义了三个函数,分别用于提取颜色、纹理和形状特征。其中,颜色特征包括每个通道的平均值和标准差,纹理特征采用LBP特征直方图,形状特征采用Hu矩。然后,定义了一个归一化图像的函数,将图像的像素值归一化到0-255之间。最后,定义了一个读取文件夹中图像并提取特征的函数,该函数返回一个特征向量矩阵。使用这个函数读取两个文件夹中的图像并提取特征,得到两个特征矩阵。最后,计算两种图像的特征差异性,分别输出颜色、纹理和形状特征的差异性

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值