亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實(shí)現(xiàn)批量圖片去重

 更新時(shí)間:2024年11月29日 09:28:43   作者:一晌小貪歡  
在日常辦公的時(shí)候,我們經(jīng)常需要對(duì)圖片進(jìn)行去重后保存,如果一張張進(jìn)行尋找將會(huì)非常的耗時(shí),下面我們就來(lái)看看如何使用Python實(shí)現(xiàn)批量圖片去重吧

1、庫(kù)的介紹

在日常辦公的時(shí)候,我們經(jīng)常需要對(duì)圖片進(jìn)行去重后保存,如果我們一張張進(jìn)行尋找,將會(huì)非常的耗時(shí),這時(shí)候我們可以利用python對(duì)圖片進(jìn)行去重處理,保留唯一項(xiàng)的圖片

2、庫(kù)的安裝

庫(kù)用途安裝
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獲取絕對(duì)路徑內(nèi)置庫(kù)無(wú)需安裝
shutil文件移動(dòng)內(nèi)置庫(kù)無(wú)需安裝

3、核心代碼

圖片去重處理

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

 if hash_value in hashes:
     self.log_output.append(f"跳過(guò)重復(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

# 設(shè)置文件夾路徑
source_folder = './圖片數(shù)據(jù)源'
result_folder = './去重后結(jié)果'

# 確保目標(biāo)文件夾存在
if not os.path.exists(result_folder):
    os.makedirs(result_folder)

# 用于存儲(chǔ)圖片的哈希值,判斷是否重復(fù)
hashes = {}

# 遍歷文件夾內(nèi)的所有圖片文件
for filename in os.listdir(source_folder):
    file_path = os.path.join(source_folder, filename)

    if os.path.isfile(file_path):
        try:
            # 讀取圖片并計(jì)算哈希值
            img = Image.open(file_path)
            hash_value = imagehash.average_hash(img)

            # 如果哈希值已存在,表示圖片重復(fù),跳過(guò)
            if hash_value in hashes:
                print(f"跳過(guò)重復(fù)圖片: {filename}")
                continue

            # 如果哈希值不重復(fù),保存圖片到目標(biāo)文件夾
            hashes[hash_value] = filename
            shutil.copy(file_path, os.path.join(result_folder, filename))
            print(f"保存圖片: {filename}")

        except Exception as e:
            print(f"無(wú)法處理圖片 {filename}: {e}")

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

到此這篇關(guān)于Python實(shí)現(xiàn)批量圖片去重的文章就介紹到這了,更多相關(guān)Python圖片去重內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論