如何将相似图像从一个文件夹分离到不同的文件夹
在本博客中,我们将讨论从文件夹中分离相似的图像。 为此,我们正在使用 python 的 imagehash
模块。 它基于图像散列。
图像散列概述
如果你不想了解图像哈希,可以跳过整个块(最好不要这样做)。 这是使用算法为图像分配值的过程。 如果两个图像看起来相同但格式不同,在捕获第二张图像时旋转、调整大小、颜色略有变化,或任何其他轻微噪音,应散列到相同的数字或更接近的数字。 尽管它们的数据的实际位完全不同,但如果它们在我们眼中看起来几乎相同,它们散列到相同的值。它们是许多类型的散列算法,例如 a-hash、p-hash……。 在这篇博文中,我们将使用 a-hash
安装
我们可以使用以下命令安装它:
$ pip install imagehash
导入所需模块
from os import listdir
from PIL import Image
import imagehash
import shutil
主要逻辑:
我们使用两个 for 循环将图像与文件夹中的其余图像一一进行比较。然后我们计算每个图像的平均哈希值,并为 hashDiff
分配一个值(此处为 35)。 如果图像相同,则两个哈希值的差异不应跨越 hashDiff
:
folder=r’name_of_the_folder_having_all_the_images’
for i in range(len(os.listdir(folder))):
for j in range(i+1,len(os.listdir(folder))):
path_0=os.path.join(folder,os.listdir(folder)[i])
path_1=os.path.join(folder,os.listdir(folder)[j])
hash_0 = imagehash.average_hash(Image.open(path_0))
hash_1 = imagehash.average_hash(Image.open(path_1))
hashDiff = 35
在下面,我们将启动一个条件来检查 hash_0
和 hash_1
是否小于 hashDiff(35)
。 如果小于 35,则表示它们是相似的图像。现在我们正在使用 shutil 模块将重复的图像移动到名为“duplicates_folder”的文件夹中。
if hash_0 - hash_1 <hashDiff:
orginal=os.path.join(folder,os.listdir(folder)[j])
target=os.path.join(r'duplicates_folder',os.listdir(folder)[j])
shutil.move(orginal,target)
下面是整个代码:
from PIL import Image
import imagehash
from os import listdir
import shutil
folder=r'name_of_the_folder_having_all_the_images'
for i in range(len(os.listdir(folder))):
for j in range(i+1,len(os.listdir(folder))):
path_0=os.path.join(folder,os.listdir(folder)[i])
path_1=os.path.join(folder,os.listdir(folder)[j])
hash_0 = imagehash.average_hash(Image.open(path_0))
hash_1 = imagehash.average_hash(Image.open(path_1))
hashDiff = 35
if hash_0 - hash_1 <hashDiff:
orginal=os.path.join(folder,os.listdir(folder)[j])
target=os.path.join(r'duplicates',os.listdir(folder)[j])
shutil.move(orginal,target)
break
print("Done")
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。