注意:我正在使用树莓派相机rev1.3,并将其设置为默认相机,而且此代码在使用默认相机的笔记本电脑上也能正常工作。
首先我已经导入了opencv和numpy库 另外,我已经输入了要使用的3个模板。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
cv2.namedWindow("cam")
template = cv2.imread('H.png',0)
template2 = cv2.imread('S.png',0)
template3 = cv2.imread('U.png',0)
w, h = template.shape[::-1]
主要问题似乎在于模板匹配部分,因为当我删除它时,代码工作得很好并且显示了非常流畅的视频。
while(True):
ret, frame = cap.read()
frame = cv2.resize(frame, (0,0), fx = 1.25, fy = 1.25)
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(frame_gray, template, cv2.TM_CCOEFF_NORMED)
res2 = cv2.matchTemplate(frame_gray, template2, cv2.TM_CCOEFF_NORMED)
res3 = cv2.matchTemplate(frame_gray, template3, cv2.TM_CCOEFF_NORMED)
threshold = 0.7
loc = np.where( res >= threshold)
loc2 = np.where( res2 >= 0.6)
loc3 = np.where( res3 >= 0.6)
for pt in zip(*loc[::-1]):
cv2.rectangle(frame, pt, (pt[0] + w+200, pt[1] + h), (255,0,0), 0)
for pt in zip(*loc2[::-1]):
cv2.rectangle(frame, pt, (pt[0] + w+200, pt[1] + h), (0,255,0), 0)
for pt in zip(*loc3[::-1]):
cv2.rectangle(frame, pt, (pt[0] + w+200, pt[1] + h), (0,0,255), 0)
cv2.imshow("cam", frame)
w = cv2.waitKey(1)
if w & 0xFF == ord('k'):
break
cap.release()
cv2.destroyAllWindows()