python:删除文件夹里的相同图片

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


需求

删除文件夹中的相同图片,保留一个即可,还希望它运行的很快,最好是多线程


直接上代码(有注释)

python 复制代码
# coding=utf-8
import os
import shutil
from loguru import logger
import threading


def match_img(img1,img2):
	#  比较图片相似度函数 值为1.0代表两图相同
    # 计算单通道的直方图的相似值  图片相似度比较
    import cv2
    def calculate(image1, image2):
        import cv2
        hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
        hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
        # 计算直方图的重合度
        degree = 0
        for i in range(len(hist1)):
            if hist1[i] != hist2[i]:
                degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
            else:
                degree = degree + 1
        degree = degree / len(hist1)
        return degree

    # 通过得到RGB每个通道的直方图来计算相似度
    def classify_hist_with_split(image1, image2, size=(256, 256)):
        # 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
        import cv2
        image1 = cv2.resize(image1, size)
        image2 = cv2.resize(image2, size)
        sub_image1 = cv2.split(image1)
        sub_image2 = cv2.split(image2)
        sub_data = 0
        for im1, im2 in zip(sub_image1, sub_image2):
            sub_data += calculate(im1, im2)
        sub_data = sub_data / 3
        return sub_data

    n = classify_hist_with_split(cv2.imread(img1), cv2.imread(img2))
    if n == 1.0:
        return n
    return n[0]

def copy_image(source_path, destination_path):
    shutil.copy(source_path, destination_path)

class MatchImg(object):

    def __init__(self):
        self.thread_lock = threading.Lock()

    def split_list(self,my_list):
        # 5000图片为一组,一组为一个线程
        chunk_size = 5000
        chunks = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]
        return chunks

    def spilt_img(self,img_list,n):
    	# 一个列表,桉顺序取出一个图片跟之后图片一一比较的方式 方法比较笨
        num = len(img_list)
        for i in range(num):
            logger.debug('第{}线程 第{}轮'.format(n,i))
            img = img_list[i]
            other_imgs = img_list[i + 1:]
            if other_imgs and os.path.exists('ct_imgs/' + img):
                self.for_img(img, other_imgs,n)

    def for_img(self,img,img_list,num):
        img_path = 'ct_imgs/'+img
        if os.path.exists(img_path):
            for i in img_list:
                i_img = 'ct_imgs/' + i
                if os.path.exists(i_img):
                    res = match_img(img_path,i_img)
                    if res == 1.0:
                        self.thread_lock.acquire()
                        logger.debug('第{}线程 删除图片路径 {}'.format(num,i_img))
                        os.remove(i_img)
                        self.thread_lock.release()

    def run(self):
        folder_path = 'ct_imgs' # 目标文件夹路径
        img_list = os.listdir(folder_path)
        print(len(img_list))
        pool = []
        split_list = self.split_list(img_list)
        for i in range(len(split_list)):
            t = threading.Thread(target=self.spilt_img,args=(split_list[i],i))
            t.start()
            pool.append(t)
        for j in pool:
            j.join()

if __name__ == '__main__':
    obj = MatchImg()
    obj.run()

总结

本代码对比算法比较中庸,欢迎指出更好的对比算法,该程序面对数据多的图片文件根据实际情况需要多次运行处理,因为这个是组内图片比较。

相关推荐
淼澄研学16 分钟前
PyTorch深度学习实战:5个核心方法从0到1构建神经网络
前端·数据库·python
SunnyDays101127 分钟前
Python 将 Excel(XLS/XLSX)转换为 JSON:导出工作簿、工作表、单元格区域与自定义 JSON 结构
python·json·excel·excel 转 json·导出 excel 到 json·xlsx 转 json·xls 转 json
天l志37 分钟前
Chrome Extension + 本地服务:浏览器页面上下文采集与远程执行技术设计
python·谷歌浏览器
CodexDave39 分钟前
Python 自动化接单实战(九):Windows 免环境交付如何打包与诊断
windows·python·自动化·python自动化·pyinstaller·软件交付·windows打包
CTA量化套保41 分钟前
2026年量化入门路线,概念规则和简单实现逐步走
人工智能·python
米码收割机1 小时前
【Python】Python Django+Vue3校园自习室预约管理系统(源码+文档+PPT)【独一无二】
开发语言·python·django
AstartesEternal1 小时前
python第二次作业(列表,字典)
开发语言·python
拉特莉的祈祷机1 小时前
绿色测试日志为什么可能已经失效:用 AET 绑定命令与当前代码
python
m沐沐1 小时前
【自然语言处理】NLP分词与Word2Vec词向量——从原理到实战
人工智能·深度学习·opencv·机器学习·计算机视觉·自然语言处理·word2vec
三金121381 小时前
Python的一些内置模块
python