from PIL import Image,ImageChops import cv2 import math from functools import reduce import operator import pytesseract def phash(img): # 这种算法的优点是简单快速,不受图片大小缩放的影响, # 缺点是图片的内容不能变更。如果在图片上加几个文字,它就认不出来了。 # 所以,它的最佳用途是根据缩略图,找出原图。 # 计算图片的局部哈希值--pHash """ :param img: 图片 :return: 返回图片的局部hash值 """ img = img.resize((8, 8), Image.ANTIALIAS).convert('L') avg = reduce(lambda x, y: x + y, img.getdata()) / 64 hash_value=reduce(lambda x, y: x | (y[1] << y[0]), enumerate(map(lambda i: 0 if i < avg else 1, img.getdata())), 0) return hash_value # 自定义计算两个图片相似度函数局部敏感哈希算法 def phash_img_similarity(img1_path,img2_path): """ :param img1_path: 图片1路径 :param img2_path: 图片2路径 :return: 图片相似度 计算图像相似度 """ # 读取图片 img1 = Image.open(img1_path) img2 = Image.open(img2_path) # 计算两个图片的局部哈希值 # 计算局部敏感哈希值 img1_phash = str(phash(img1)) img2_phash = str(phash(img2)) # 打印局部敏感哈希值 # print(img1_phash) # print(img2_phash) distance = bin(phash(img1) ^ phash(img2)).count('1') # print(distance) # print(max(len(bin(phash(img1))), len(bin(phash(img1))))) similary = 1 - distance / max(len(bin(phash(img1))), len(bin(phash(img1)))) return similary def image_contrast(img1,img2): '''3.图像对比''' image1 = Image.open(img1) image2 = Image.open(img2) h1 = image1.histogram() h2 = image2.histogram() result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1)) return result def image_contrast(img1,img2): '''3.图像对比''' image1 = Image.open(img1) image2 = Image.open(img2) h1 = image1.histogram() h2 = image2.histogram() result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1)) return result def compare_images(img_one,img_two): '''对比两张图片是否相同''' image_one=Image.open(img_one) image_two=Image.open(img_two) try: diff=ImageChops.difference(image_one,image_two) if diff.getbbox() is None: print("【+】We are the same!") return True else: return False except ValueError as e: text = ("图片不一样") print("【{0}】{1}".format(e, text)) return None def cut_image(png,new_png): '''对图片进行部分图片截取 ''' img=Image.open(png) cropped=img.crop((0, 810, 2000, 2280))#x1,y1,x2,y2 cropped.save(new_png)
图片相似度和是否相同
猜你喜欢
转载自blog.csdn.net/liming066/article/details/88054536
今日推荐
周排行