python图片去重
网上爬取图片后有很多重复的图片,本示例通过python的imagehash库对图片进行去重
- 导入相应的包
import os
import numpy as np
import cv2
from PIL import Image
import imagehash
- 生成图片的hash编码
此步骤会生成当前目录下的所有图片的hash编码值,并保存为txt文件
files = os.listdir('./') # image path
files = np.array([file for file in files if file.endswith('jpg')])
fp = open('hash.txt', 'w')
for file in files:
img = cv2.imread(file)
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
hash_code = imagehash.phash(img)
fp.write(str(hash_code) + ' ' + file + '\n')
fp.close()
- 图像去重
比较图片的hash编码值用于去重
fp = open('hash.txt', 'r')
lines = fp.readlines()
lines = [line.strip().split() for line in lines]
fp.close()
for i in range(0, len(lines) - 1, 1):
for j in range(i + 1, len(lines), 1):
if lines[i][0] == lines[j][0]:
print(lines[i])
os.remove(lines[i][1])
break