当前位置: 代码网 > it编程>前端脚本>Python > Python实现批量图片去重

Python实现批量图片去重

2024年11月30日 Python 我要评论
1、库的介绍在日常办公的时候,我们经常需要对图片进行去重后保存,如果我们一张张进行寻找,将会非常的耗时,这时候我们可以利用python对图片进行去重处理,保留唯一项的图片2、库的安装库用途安装pill

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图片去重内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com