我的帧差分(前景检测)工作得很好。现在,我想在其中添加一个额外的功能,即斑点检测。基本上,我的想法是在检测到的物体的运动上形成斑点圆圈。
这是我的代码:
import cv2
cap = cv2.VideoCapture('14.mp4')
ret, current_frame = cap.read()
previous_frame = current_frame
# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()
# Change blob detection thresholds
params.minThreshold = 200
params.maxThreshold = 255
params.minDistBetweenBlobs = 100
# Filter by Area.
params.filterByArea = True
params.minArea = 1200
params.maxArea = 40000
# Filter by Circularity
params.filterByCircularity = False
params.minCircularity = 0.1
# Filter by Convexity
params.filterByConvexity = False
params.minConvexity = 0.87
# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.02
# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)
#Detect blobs
keypoints = detector.detect(current_frame)
while(cap.isOpened()):
current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)
frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray)
im_with_keypoints = cv2.drawKeypoints(frame_diff, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow('frame diff ',im_with_keypoints )
if cv2.waitKey(1) & 0xFF == ord('q'):
break
previous_frame = current_frame.copy()
ret, current_frame = cap.read()
keypoints = detector.detect(current_frame)
cap.release()
cv2.destroyAllWindows()
我的错误是"图像不是数字,也不是标量"
你正在将cap
变量传递给函数 detector.detect
,但cap
来自返回 CvCapture 对象而不是 Numpy 数组的cv2.VideoCapture
。
相反,您应该使用 .read()
返回的current_frame
。
keypoints = detector.detect(current_frame)
你应该导入库"numpy"
你可以在你的cmd(win+R,cmd,enter)上建立它:pip install numpy
并编写代码:将 numpy 导入为 np
此问题是由阈值参数引起的,主要是params.minThreshold = 100
和params.maxThreshold = 255
。为什么要设置这些特定值?尝试对它们进行周转,直到获得良好的结果。
附带说明一下,您似乎没有收到此错误,但是在我的一个.avi视频上运行您的代码时,我收到了 cv2.error。我通过将while(cap.isOpened()):
更改为while(ret)
来修复它。