在本地的多张图片里指定一张图片,并通过颜色直方图特征查找相似图片,python实现
时间: 2023-10-05 13:13:58 浏览: 61
首先,需要导入以下库:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
```
然后,读取指定图片和多张本地图片:
```python
# 读取指定图片
img = cv2.imread('指定图片的路径')
# 读取多张本地图片
img_list = []
for i in range(1, 6):
img_list.append(cv2.imread(f'本地图片{i}.jpg'))
```
接着,计算指定图片的颜色直方图特征:
```python
# 计算指定图片的颜色直方图特征
bins = 8
hist = cv2.calcHist([img], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist, hist).flatten()
```
最后,计算多张本地图片与指定图片的颜色直方图相似度,并返回相似度最高的图片:
```python
# 计算多张本地图片与指定图片的颜色直方图相似度
max_sim = 0
max_idx = -1
for i, img_i in enumerate(img_list):
hist_i = cv2.calcHist([img_i], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])
hist_i = cv2.normalize(hist_i, hist_i).flatten()
sim = cv2.compareHist(hist, hist_i, cv2.HISTCMP_CORREL)
if sim > max_sim:
max_sim = sim
max_idx = i
# 返回相似度最高的图片
plt.figure(figsize=(10, 10))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('指定图片')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(img_list[max_idx], cv2.COLOR_BGR2RGB))
plt.title(f'相似度最高的本地图片{max_idx+1}')
plt.axis('off')
plt.show()
```
完整代码如下:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取指定图片
img = cv2.imread('指定图片的路径')
# 读取多张本地图片
img_list = []
for i in range(1, 6):
img_list.append(cv2.imread(f'本地图片{i}.jpg'))
# 计算指定图片的颜色直方图特征
bins = 8
hist = cv2.calcHist([img], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist, hist).flatten()
# 计算多张本地图片与指定图片的颜色直方图相似度
max_sim = 0
max_idx = -1
for i, img_i in enumerate(img_list):
hist_i = cv2.calcHist([img_i], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])
hist_i = cv2.normalize(hist_i, hist_i).flatten()
sim = cv2.compareHist(hist, hist_i, cv2.HISTCMP_CORREL)
if sim > max_sim:
max_sim = sim
max_idx = i
# 返回相似度最高的图片
plt.figure(figsize=(10, 10))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('指定图片')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(img_list[max_idx], cv2.COLOR_BGR2RGB))
plt.title(f'相似度最高的本地图片{max_idx+1}')
plt.axis('off')
plt.show()
```
阅读全文