python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python图片去重

Python实现批量图片去重

作者:一晌小贪欢

在日常办公的时候,我们经常需要对图片进行去重后保存,如果一张张进行寻找将会非常的耗时,下面我们就来看看如何使用Python实现批量图片去重吧

1、库的介绍

在日常办公的时候,我们经常需要对图片进行去重后保存,如果我们一张张进行寻找,将会非常的耗时,这时候我们可以利用python对图片进行去重处理,保留唯一项的图片

2、库的安装

用途安装
Pillow图片处理pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple/
imagehash图片处理pip install imagehash -i https://pypi.tuna.tsinghua.edu.cn/simple/
os获取绝对路径内置库无需安装
shutil文件移动内置库无需安装

3、核心代码

图片去重处理

img = Image.open(file_path)
hash_value = imagehash.average_hash(img)

 if hash_value in hashes:
     self.log_output.append(f"跳过重复图片: {filename}")

4、完整代码

# -*- coding: UTF-8 -*-
'''
@Project :图片去重
@File    :图片去重.py
@IDE     :PyCharm 
@Author  :一晌小贪欢(278865463@qq.com)
@Date    :2024/11/6 10:04 
'''

import os
import hashlib
from PIL import Image
import imagehash
import shutil

# 设置文件夹路径
source_folder = './图片数据源'
result_folder = './去重后结果'

# 确保目标文件夹存在
if not os.path.exists(result_folder):
    os.makedirs(result_folder)

# 用于存储图片的哈希值,判断是否重复
hashes = {}

# 遍历文件夹内的所有图片文件
for filename in os.listdir(source_folder):
    file_path = os.path.join(source_folder, filename)

    if os.path.isfile(file_path):
        try:
            # 读取图片并计算哈希值
            img = Image.open(file_path)
            hash_value = imagehash.average_hash(img)

            # 如果哈希值已存在,表示图片重复,跳过
            if hash_value in hashes:
                print(f"跳过重复图片: {filename}")
                continue

            # 如果哈希值不重复,保存图片到目标文件夹
            hashes[hash_value] = filename
            shutil.copy(file_path, os.path.join(result_folder, filename))
            print(f"保存图片: {filename}")

        except Exception as e:
            print(f"无法处理图片 {filename}: {e}")

print("图片去重完成!")

到此这篇关于Python实现批量图片去重的文章就介绍到这了,更多相关Python图片去重内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文