opencv 利用哈希值算法大批量删除数据集中重复的图片
时间: 2023-12-30 21:04:19 浏览: 35
你可以使用哈希值算法来检测和删除数据集中的重复图片。一种常用的哈希算法是感知哈希算法(Perceptual Hashing),它可以将图片转换成一个唯一的哈希值。以下是使用OpenCV和Python进行大批量删除重复图片的基本步骤:
1. 导入所需的库:
```python
import os
import cv2
import imagehash
from PIL import Image
```
2. 定义一个函数来计算图片的哈希值:
```python
def calculate_hash(image_path):
image = Image.open(image_path)
image_hash = imagehash.average_hash(image)
return str(image_hash)
```
3. 创建一个空字典来存储每个哈希值及其对应的图片路径:
```python
hash_dict = {}
```
4. 遍历数据集中的每张图片,计算其哈希值,并将哈希值及其对应的图片路径存储在字典中:
```python
dataset_path = 'your_dataset_path'
for root, dirs, files in os.walk(dataset_path):
for file in files:
image_path = os.path.join(root, file)
image_hash = calculate_hash(image_path)
if image_hash in hash_dict:
hash_dict[image_hash].append(image_path)
else:
hash_dict[image_hash] = [image_path]
```
5. 遍历字典中的每个哈希值,如果该哈希值对应的图片路径数量大于1,则删除重复图片(保留一张即可):
```python
for image_hash, image_paths in hash_dict.items():
if len(image_paths) > 1:
for i in range(1, len(image_paths)):
os.remove(image_paths[i])
```
注意:在删除图片之前,请务必备份你的数据集,以防止误删。
这是一个基本的示例,你可以根据自己的需求进行相应的修改和优化。希望能对你有所帮助!