python opencv图像识别(相同大小图片)
简介
由于项目需要对比两张相同图片的相似度,因此采用opencv将图片转为灰阶数组,然后对比相应的数组来取相似度,此方法只适用于大小相同的图片,较为局限
# -*- coding: utf-8 -*-
import cv2
import os
# scikit-image
from skimage.metrics import structural_similarity as ssim
class PictureSimilarity():
"""
Image cutting and image recognition
Parameters:
origin_img: 起始图片
compare_img: 需要对比的图片
start_x: 裁切的起始x轴
start_y: 裁切的起始y轴
end_x: 裁切的末尾x轴
end_y: 裁切的末尾y轴
"""
def __init__(self, origin_img, compare_img, start_y=None, end_y=None, start_x=None, end_x=None):
self.origin_img = origin_img[0]
self.compare_img = compare_img[0]
self.start_x = start_x
self.start_y = start_y
self.end_x = end_x
self.end_y = end_y
def compute_Similarity(self):
try:
print(f"compute acquaintance")
image1 = cv2.imread(self.origin_img)
image2 = cv2.imread(self.compare_img)
if self.start_x is not None:
image1 = image1[int(self.start_y):int(self.end_y), int(self.start_x):int(self.end_x)]
cut_img = "{}_cut.png".format(os.path.splitext(self.origin_img)[0])
cv2.imwrite(cut_img, image1)
else:
image1 = image1
height1, wide1 = image1.shape[0:2]
if not height1 or not wide1:
print("Picture coordinate error, screenshot size cannot be zero")
if image1.shape != image2.shape:
print("Inconsistent picture size")
# 会强制拉伸图片
image2 = cv2.resize(image2, (image1.shape[1],image1.shape[0]))
resize_img = "{}_resize.png".format(os.path.splitext(self.compare_img)[0])
cv2.imwrite(resize_img, image2)
image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
acquaintance = ssim(image1, image2)
acquaintance = acquaintance*100
acquaintance = round(acquaintance, 2)
print(f"acquaintance is {acquaintance}")
return acquaintance
except Exception as e:
print(f"compute_Similarity error is {str(e)}")
def compute_img(self):
Similarity = None
try:
print(f"start compute acquaintance")
print(self.origin_img)
if os.path.exists(self.origin_img) and os.path.exists(self.compare_img):
Similarity = self.compute_Similarity()
else:
print("content not exist")
except Exception as e:
print(f"compute_img error is {str(e)}")
finally:
return Similarity
if __name__ == "__main__":
image_path1 = "/home/ts/workspace/image2_2.png",
image_path2 = "/home/ts/workspace/image2.png",
test = PictureSimilarity(image_path1, image_path2, 12,189,23,400)
result = test.compute_img()
print(result)
分类:
python常用方法、函数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了