通过Python实现图片去重是很有用的技能,因为我们经常需要去管理和组织大量的图片,但是会有很多重复的图片占据硬盘空间。这篇文章将会从多个角度介绍如何用Python实现图片去重。
一、用哈希算法判断图片是否相同
判断两张图片是否相同通常需要比较它们像素点的值,所以很难直接判断。但是,只要两张图片的哈希值相同,就可以判断它们是相同的。这是因为哈希算法可以将图片转换成一个数字,只要两张图片转换后得到的数字是相同的,那么这两张图片就是相同的。
下面是基于Pillow库实现的哈希算法:
from PIL import Image
import imagehash
# Load the image
image = Image.open("image.jpg")
# Calculate the hash
hash = imagehash.average_hash(image)
# Print the hash
print(hash)
通过将图片转换成一个哈希值,我们可以轻松的判断两张图片是否相同。
二、删除重复的图片
找到重复的图片之后,我们就可以把它们删除了。下面的代码实现了如何找到索引列表中的重复项:
def get_duplicates_indexes(lst):
return [i for i, x in enumerate(lst) if lst.count(x) > 1]
# Example usage:
lst = [0, 1, 2, 3, 3, 4, 5, 5]
print(get_duplicates_indexes(lst))
这个函数可以返回索引列表中所有的重复项的位置。
接下来,我们可以用以下代码删除重复的图片:
import os
# The folder to search for duplicates
folder = "example_folder"
# Get all the files in the folder
files = os.listdir(folder)
# Get the hashes of all the files
hashes = []
for file in files:
filepath = os.path.join(folder, file)
if os.path.isfile(filepath):
image = Image.open(filepath)
hash = imagehash.average_hash(image)
hashes.append(hash)
# Get the indexes of the duplicates
duplicate_indexes = get_duplicates_indexes(hashes)
# Delete the duplicates
for index in sorted(duplicate_indexes, reverse=True):
filepath = os.path.join(folder, files[index])
os.remove(filepath)
这段代码将所有图片的哈希值存储到了一个列表中,然后找到所有重复的哈希值,并删除其中的一个文件。
三、以文件大小和图像的尺寸进行比较
有时候,两张图片虽然内容不同,但它们的尺寸和大小相同。因此,我们可以以文件大小和图像的尺寸进行比较,来判断两张图片是否重复。
以下代码演示如何比较图像的尺寸:
image1 = Image.open("image1.jpg")
image2 = Image.open("image2.jpg")
if image1.size == image2.size:
print("Images are the same size.")
else:
print("Images are different sizes.")
以上代码比较了两张图片的尺寸,因此我们可以判断它们是否相同。
以下代码演示如何比较两个文件的大小:
import os
file1_size = os.path.getsize("file1.jpg")
file2_size = os.path.getsize("file2.jpg")
if file1_size == file2_size:
print("Files are the same size.")
else:
print("Files are different sizes.")
以上代码比较了两个文件的大小,因此我们可以判断它们是否相同。
四、从图像中提取特征值
另一种用于比较两张图片是否相同的方法是,在图像中提取特征值,并将这些值用于比较。以下代码演示了如何提取图像的特征值:
from skimage.feature import hog
from skimage import data, exposure
# Load the image
image = data.astronaut()
# Extract the feature vector
fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
cells_per_block=(1, 1), visualize=True, multichannel=True)
# Plot the original and HOG images
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax2.imshow(hog_image, cmap=plt.cm.gray)
ax2.set_title('Histogram of oriented gradients')
以上代码使用了贡献于Scikit-Image的HOG算法。它将图像划分成许多小区域,然后计算每个区域内的梯度直方图。使用这种方法,我们可以轻松地将两张图片进行比较并找到它们的相似之处。
总结
通过上述几种方法,我们可以使用Python实现图片去重操作。这些方法包括使用哈希算法、删除重复图片、比较图像大小和尺寸以及从图像中提取特征值。根据你的需求,可以选择其中任何一种来判断是否存在重复图片并将它们删除。