我正在尝试修复一个错误,即当两个矩形在视频中发生碰撞时,它们会合并为一个大矩形以用于碰撞的其余帧,而不是像以前一样保留矩形:
即使物体发生碰撞,我也想保留两个矩形。
主循环片段:
while True:
ret, frame = vid.read()
if frame is None:
break
# TRESH_OTSU has problems with objects that are very dark
bright_frame = cv2.addWeighted(
frame, 4.3, np.zeros(frame.shape, frame.dtype), 0, 20
)
# create a mask that will remove the black background from tracking
gray = cv2.cvtColor(bright_frame, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# get the moving objects
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
detections = []
for obj in contours:
area = cv2.contourArea(obj)
if area > 50: # filter noise
perimeter = cv2.arcLength(obj, True)
approx = cv2.approxPolyDP(obj, 0.02 * perimeter, True)
object_type = "rectangle" if len(approx) == 4 else "circle"
x, y, w, h = cv2.boundingRect(obj)
detections.append(
DetectedObject(
x, y, w, h, get_obj_color(frame, x, y, w, h), object_type
)
)
rects = tracker.update(detections)
for rect in rects:
x, y, w, h, id, _, _, time = rect
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255), 5)
# cv2.putText(
# frame, str(id), (x, y - 15), cv2.FONT_HERSHEY_PLAIN, 5, (255, 255, 255)
# )
print(rect)
cv2.imshow("frame", frame)
key = cv2.waitKey(10)
# break the loop upon the press of esc
if key == 27:
break
这是我的意思的一个例子。我做了一个小例子,因为你没有提供未处理的图像:
分离:
碰撞:
方法非常简单:
cv2.inRange
对于失散的人:
对于碰撞:
代码片段:
# define boundary for first object
lower1 = (150,90,30)
upper1 = (170,110,60)
# define boundary for second object
lower2 = (150,150,150)
upper2 = (255,255,255)
# get bounding boxes
boundingRect1 = cv2.boundingRect(cv2.inRange(im,lower1,upper1))
boundingRect2 = cv2.boundingRect(cv2.inRange(im,lower2,upper2))
# draw rectangle on im
cv2.rectangle(im, boundingRect1, (255,0,0), 5)
cv2.rectangle(im, boundingRect2, (0,0,255), 5)
我不确定你最终会拥有多少个物体,我也不确定这两个物体是否可以按颜色分开。如果你总是有像照片这样干净的对象,最终看看连接的组件