图片相似度和是否相同

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值