我正在处理来自摄像头的视频流。我正在使用opencv捕获和显示视频。 我的目标是将视频显示窗口分成3个具有指定宽度和高度的矩形。当在矩形中检测到对象时,则应输出左中心或右中心。我设法计算出对象的中心坐标,并在视频流显示窗口上绘制了矩形。根据其落在矩形之一中的坐标,输出将为左,中或右。
我的问题是,当坐标落在其中一个框内时,如何进行输出。我假设在框中使用if center_coord然后输出,但它不起作用。
import cv2
from darkflow.net.build import TFNet
import numpy as np
import time
from collections import namedtuple
options = {
'model': 'cfg/yolov2.cfg',
'load': 'bin/yolov2.weights',
'threshold': 0.8,
'gpu': 0.8
}
tfnet = TFNet(options)
colors = [tuple(255 * np.random.rand(3)) for _ in range(10)]
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
center_coord = namedtuple("center_coord", ['x', 'y'])
while True:
stime = time.time()
ret, frame = capture.read()
box = cv2.rectangle(frame, (1, 0), (426, 720), (0, 0, 255), 2)
box2 = cv2.rectangle(frame, (426, 0), (852, 720), (0, 0, 255), 2)
box3 = cv2.rectangle(frame, (852, 0), (1279, 720), (0, 0, 255), 2)
if ret:
results = tfnet.return_predict(frame)
for color, result in zip(colors, results):
tl = (result['topleft']['x'], result['topleft']['y'])
br = (result['bottomright']['x'], result['bottomright']['y'])
center_x = ((tl[0] + br[0])/2)
center_y = ((tl[1] + br[1])/2)
center_box = center_coord(center_x, center_y)
print(center_box)
label = result['label']
confidence = result['confidence']
text = '{}: {:.0f}%'.format(label, confidence * 100)
frame = cv2.rectangle(frame, tl, br, color, 5)
frame = cv2.putText(frame, text, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2)
cv2.imshow('frame', frame)
print('FPS {:.1f}'.format(1 / (time.time() - stime)))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
capture.release()
cv2.destroyAllWindows()
答案 0 :(得分:0)
我通过使用简单的if else语句(根据我的分辨率窗口的宽度在x坐标范围内)来做到这一点。
def box_tracking(self, center):
self.center = center
while True:
if 0 <= center <= 426:
center = -1
print("Object on left")
elif 426 < center <= 852:
center = 0
print("Object on center")
elif 852 < center <= 1280:
center = 1
print("Object on right")
else:
center = 2
print("No object detected")
break
luggage_arduino.Arduino(center)