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