python 圖片去重復 你值得擁有imagededup


現實中我們經常需要用到圖像去重,比如為了擴充人臉圖像,可以在百度、Google通過關鍵詞下載大量人臉圖像,但這些圖像可能存在重復,在合並時需要去重。

 

 

 

開源地址:

https://github.com/idealo/imagededup

該庫於今年4月份開源,已經有1600+顆星,最近兩天還沖上了Github趨勢榜。

可以使用 pip 直接安裝:

pip install imagededup

 

僅需要 4 行代碼即可實現圖像去重:

from imagededup.methods import PHash
phasher = PHash()

# 生成圖像目錄中所有圖像的二值hash編碼
encodings = phasher.encode_images(image_dir='path/to/image/directory')

# 對已編碼圖像尋找重復圖像
duplicates = phasher.find_duplicates(encoding_map=encodings)

# 給定一幅圖像,顯示與其重復的圖像
from imagededup.utils import plot_duplicates
plot_duplicates(image_dir='path/to/image/directory',
                duplicate_map=duplicates,
                filename='ukbench00120.jpg')

 

 

 

項目中應用實例

 

"""
圖片去重
"""
import os
from imagededup.methods import PHash


def process_file(img_path):
    """
    處理圖片去重
    :return:
    """
    try:
        phasher = PHash()
        # 生成圖像目錄中所有圖像的二值hash編碼
        encodings = phasher.encode_images(image_dir=img_path)
        # print(encodings)
        # 對已編碼圖像尋找重復圖像
        duplicates = phasher.find_duplicates(encoding_map=encodings)
        # print(duplicates)
        only_img = []  # 唯一圖片
        like_img = []  # 相似圖片

        for img, img_list in duplicates.items():
            if ".png" in img:
                continue
            if img not in only_img and img not in like_img:
                only_img.append(img)
                like_img.extend(img_list)

        # 刪除文件
        for like in like_img:
            like_src = os.path.join(img_path, like)
            png_src = like_src[:-4] + ".png"
            if os.path.exists(like_src):
                os.remove(like_src)
            if os.path.exists(png_src):
                os.remove(png_src)

    except Exception as e:
        print(e)


if __name__ == "__main__":
    img_path = "/tmp/t3/"

    num = 0
    for root, dirs, files in os.walk(img_path):
        for dir in dirs:
            file_dir_path = os.path.join(root, dir)
            process_file(file_dir_path)
            num += 1
            print("處理文件夾個數:{}".format(num))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM