我正在尝试通过网络摄像头进行对象检测(检测手机),但是我的代码未执行。以下是我的代码:
import cv2
import numpy as np
def sift_detector(new_image,image_template):
#Function that compares input image to template.
#it then returns the number of sift matches between them
image1 = cv2.cvtColor(new_image,cv2.COLOR_BGR2GRAY)
image2 = image_template
# create a sift dectector object
#sift = cv2.sift()
sift = cv2.xfeatures2d.SIFT_create()
#obtain the keypoints and descriptors usng SIFT
keypoints_1,descriptors_1 = sift.detectAndCompute(image1 , None)
keypoints_2,descriptors_2 = sift.detectAndCompute(image2 , None)
#define parameters for our flann matcher
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE,tress = 3)
search_params = dict(checks = 100)
#create the flann matcher object
flann = cv2.FlannBasedMatcher(index_params,search_params)
# obtain matches using knn method
# the result 'matchs' is the number of similar matches found in both images
matches = flann.knnMatch(descriptors_1,descriptors_2,k = 2)
# Store good matches using lowe's ratio test
good_matches=[]
for m,n in matches:
if m.distance < 0.7 *n.distance:
good_matches.append(m)
return len(good_matches)
这是我用来检测物体的SIFT检测器功能 下面是VideoCapture代码:
cap = cv2.VideoCapture(0)
# laod image template, this is our reference image
image_template = cv2.imread('images/iphone.jpg',0)
while True:
#get webcam images
ret,frame = cap.read()
#get height and width of webcam frame
height,width = 480,640
#Define ROI BOX Dimensions
top_left_x = int (width / 3)
top_left_y = int((height / 2) + (height / 4))
bottom_right_x = int((width / 3) * 2 )
bottom_right_y = int( (height / 2) - (height / 4) )
# Draw rectangular window of our region of interest
cv2.rectangle(frame,(top_left_x,top_left_y),
(bottom_right_x,bottom_right_y),255 , 3)
# crop window of observation we define above
cropped = frame[bottom_right_y:top_left_y,top_left_x :bottom_right_x]
# flip frame orientation horizontally
frame = cv2.flip(frame,1)
# get number of sift matches
matches = sift_detector(cropped,image_template)
#display status string showing the current no of matches
cv2.putText(frame,str(matches),(450,450),cv2.FONT_HERSHEY_COMPLEX,2,
(0,0,255),1)
#our threshold to indicate object detection
# we use 10 since the sift detector returns little false positives
threshold = 10
# if matches exceed our threshold then object has been detected
if matches > threshold :
cv2.rectangle(frame,(top_left_x,top_left_y),
(bottom_right_x,bottom_right_y),(0,0,255),3)
cv2.putText(frame,'object found',(50,50),cv2.FONT_HERSHEY_COMPLEX,2,
(0,0,255),2)
cv2.imshow('object detector using sift',frame)
if cv2.waitKey(1) == 13: #13 is enter key
break
cap.release()
cv2.destroyAllWindows()
当我尝试解决一个错误时,会弹出其他错误。我得到的最常见的错误是NoneType错误。我想知道是否还有其他我可以参考的代码。我是该领域的初学者。