python Opencv对重复图片或者类似图片进行删除

两种算法的实现方式,基本类似

第一种:ssim 算法

导入包

from skimage.metrics import structural_similarity as ssim

第二种:psnr 算法

导入包

from skimage.metrics import peak_signal_noise_ratio as psnr

注意:

1、两张照片大小必须一样,如:尺寸1980*1080大小

2、通道数量必须一样,也就是彩色图必须与彩色图像,灰色必须是灰色图像(这样更精确)

查看通道数的方法,

3、数组维度必须一样,图片用代码表示,其实就是一个多维数组

图片的np矩阵,一般cv2读取图片的能用使用这个属性

print(img.shape)
==> (图片x轴的长度(第一位数组的个数),图片y轴的长度(二维数组的个数),通道数)

彩色和灰色的区别:
彩色为3维数组
灰色为2维数组

通道数:
单通道,为灰度图
双通道,有,但是我也不太了解,大家如果有兴趣的话,可以自行百度以下
三通道,为彩色图,(R,G,B)
四通道,在三通道上加了一个透明度,(R,G,B,A),A表示透明度,一般叫做alpha通道

下面是代码部分

import os
import sys
import cv2
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import peak_signal_noise_ratio as psnr

获取文件夹下的所有子文件夹名称
def ImageAllPath(pathFile):
    ImagePath_list = os.listdir(pathFile)
    print(len(ImagePath_list))
    return ImagePath_list

进行图片相似度比对
def ImageFor():
    # 图片文件夹
    pathFile = r"你图片文件夹绝对路径"
    ImagePath_list = ImageAllPath(pathFile)
    print(ImagePath_list)
    for index in range(len(ImagePath_list)-1):

        print(pathFile+'\\'+ImagePath_list[index])
        path =pathFile+'\\'+ImagePath_list[index]
        # 判断照片是否存在
        if os.path.exists(path):

            # 读取第一张照片
            img1 = cv2.imread(path)
            img1_gray=cv2.resize(img1,(1920,1080))
            # 读取第二张照片
            path = pathFile+ '\\' + ImagePath_list[index+1]
            img2 = cv2.imread(path)
            print("img2:"+path)
            # img2_gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
            img2_gray = cv2.resize(img2, (1920,1080))
            """" 第一种算法对比 """
            # 可视化展示照片
            # cv2.imshow("img1_gray",img1_gray)
            # cv2.imshow("img2_gray", img2_gray)
            # cv2.moveWindow("img1_gray",0,0)
            # cv2.moveWindow("img2_gray", img1_gray.shape[0], 0)
            # # 进行算法比对
            # ss = ssim(img1_gray,img2_gray)
            # if ss > 0.7:
            #     print("相似")
            # else:
            #     print("不相似")

            """ 第二种算法对比 """
            img1_gray1=img1_gray[208:1060,455:1000]
            img2_gray2 = img2_gray[208:1060,455:1000]
            ss1 = psnr(img1_gray1, img2_gray2)
            cv2.imshow("img1_gray1", img1_gray1)
            cv2.imshow("img2_gray2", img2_gray2)
            cv2.moveWindow("img1_gray1", 300, 0)
            cv2.moveWindow("img2_gray2", img1_gray1.shape[0], 0)
            # 相似图如果大于16 进行删除
            if ss1 >16 :
                # 删除图片
                os.remove(path)

            print(ss1)
            # 停留1毫秒
            cv2.waitKey(1)

if __name__ == '__main__':

    ImageFor()

佩奇也是才刚刚开始学习opencv,如果有讲的不对的地方,请在评论区评论,佩奇收到后会及时更新,以免误导他人。

祝我们一起进步,加油!!

Original: https://blog.csdn.net/m0_65833575/article/details/126162412
Author: 源源佩奇
Title: python Opencv对重复图片或者类似图片进行删除

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/637527/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球