使用AverageHash算法编写程序 1.使用python 2.使用摄像头 3.文件夹保存模板图片 4.摄像头显示找到类似的图片 5.一张图片里可以匹配多个
时间: 2024-05-05 11:15:25 浏览: 180
物体
以下是使用Python编写的一个基本的AverageHash算法程序,它使用摄像头捕捉实时视频并与保存在文件夹中的模板图像进行匹配。对于每个匹配,程序将在摄像头显示器上显示框,以突出显示找到的物体。
```python
import cv2
import os
import numpy as np
# 读取模板图像,并计算其哈希值
def load_images():
images = []
hashes = []
for file in os.listdir("templates"):
image = cv2.imread(os.path.join("templates", file))
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (8, 8), interpolation=cv2.INTER_AREA)
images.append(image)
avg = np.mean(image)
hash = 0
for i in range(8):
for j in range(8):
if image[i, j] > avg:
hash |= 1 << (i * 8 + j)
hashes.append(hash)
return images, hashes
# 计算输入图像的哈希值,并与模板图像逐一比较
def find_matches(images, hashes, frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray, (8, 8), interpolation=cv2.INTER_AREA)
avg = np.mean(gray)
hash = 0
for i in range(8):
for j in range(8):
if gray[i, j] > avg:
hash |= 1 << (i * 8 + j)
matches = []
for i in range(len(hashes)):
dist = bin(hashes[i] ^ hash).count('1')
if dist < 5:
matches.append(images[i])
return matches
# 循环捕捉视频帧,并查找匹配的图像
def main():
images, hashes = load_images()
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
matches = find_matches(images, hashes, frame)
for match in matches:
res = cv2.matchTemplate(frame, match, cv2.TM_CCOEFF_NORMED)
loc = np.where(res >= 0.8)
for pt in zip(*loc[::-1]):
cv2.rectangle(frame, pt, (pt[0]+match.shape[1], pt[1]+match.shape[0]), (0, 0, 255), 2)
cv2.imshow("frame", frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
```
这个程序首先读取文件夹中的所有模板图像,并计算它们的哈希值。在循环捕捉视频帧时,程序计算输入帧的哈希值,并与每个模板图像的哈希值逐一比较。如果匹配成功,则程序使用OpenCV的matchTemplate函数查找匹配的位置,并在摄像头显示器上显示一个红色矩形框来突出显示找到的物体。
请注意,这个程序使用的AverageHash算法非常简单,并且可能无法处理一些复杂场景,例如光线变化、旋转、缩放等。对于更复杂的场景,建议使用更强大的算法,例如SIFT、SURF或ORB。
阅读全文
相关推荐















