gpt4 book ai didi

python - 如何使用Python的OpenCV跟踪2个对象的位置?

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:16 25 4
gpt4 key购买 nike

关在笼子里的两只老鼠。到目前为止,我已经执行了背景扣除,因此只能看到小鼠。我的最终目标是跟踪两只老鼠在笼子中移动时的位置与时间的关系,但我无法弄清楚。我想让两只老鼠的位置出现在屏幕上,也许它们在四处移动时以x-y坐标显示。到目前为止,我已经附加了我的代码。任何帮助,将不胜感激!


import cv2
import numpy as np

THRESHOLD_ANIMAL_VS_FLOOR = 70
BGR_COLOR = {'red': (0, 0, 255),
'green': (127, 255, 0),
'blue': (255, 127, 0),
'yellow': (0, 127, 255),
'black': (0, 0, 0),
'white': (255, 255, 255)}
cap = cv2.VideoCapture('IMG_0224_Trim3.mp4')
h, w = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(
cap.get(cv2.CAP_PROP_FRAME_WIDTH))

# Check if camera opened successfully
if (cap.isOpened() == False):
print("Error opening video stream or file")

# Read until video is completed
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
# Convert BGR to GRAY
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
kernelSize = (5, 5)
frameBlur = cv2.GaussianBlur(gray, kernelSize, 0)
_, thresh = cv2.threshold(
frameBlur, THRESHOLD_ANIMAL_VS_FLOOR, 255, cv2.THRESH_BINARY)
mask = cv2.inRange(thresh, (0, 0, 0, 0), (180, 250, 30, 0))
contours, hierarchy = cv2.findContours(
thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for contour in contours:
cv2.drawContours(frame, contour, -1, BGR_COLOR['green'], 3, maxLevel=1)

#object tracking ---------------------------------



#-----------------------

cv2.imshow("Frame", frame)
cv2.imshow('mask', mask)

k = cv2.waitKey(5) & 0xFF
if (k == 113): # press q to quit
break

cv2.destroyAllWindows()

最佳答案

您可以编写如下代码:

for contour in contours:
the_size = cv.contourArea(cnt)
M = cv.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
if the_size > A_THRESHOLD:
cv2.puText(frame, "%d,%d"%(cx,cy), (cx,cy), cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),1,cv2.LINE_AA)

关于python - 如何使用Python的OpenCV跟踪2个对象的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com