python - 在 OpenCV 中设置 ROI
问题描述
我对 OpenCV 和 Python 很陌生。我已经按照教程使用 yolov3-tiny 使用 YOLO。它可以很好地检测车辆。但是我需要完成我的项目是计算通过特定车道的车辆数量。如果我使用检测到车辆(出现边界框)的方法进行计数,则计数变得非常不准确,因为边界框不断闪烁(意味着它会再次定位同一辆车,有时最多 5 次),所以这不是一个好的计数方法。所以我想,如果我只计算一辆车,如果它到达某个点怎么样。我见过很多似乎可以做到这一点的代码,但是,因为我是初学者,我真的很难理解,更不用说在我的系统中运行它了。他们的示例需要安装很多我不能做的东西,因为它会引发错误。
cap = cv2.VideoCapture('rtsp://username:password@xxx.xxx.xxx.xxx:xxx/cam/realmonitor?channel=1')
whT = 320
confThreshold = 0.75
nmsThreshold = 0.3
list_of_vehicles = ["bicycle","car","motorbike","bus","truck"]
classesFile = 'coco.names'
classNames = []
with open(classesFile, 'r') as f:
classNames = f.read().rstrip('\n').split('\n')
modelConfiguration = 'yolov3-tiny.cfg'
modelWeights = 'yolov3-tiny.weights'
net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
total_vehicle_count = 0
def getVehicleCount(boxes, class_name):
global total_vehicle_count
dict_vehicle_count = {}
if(class_name in list_of_vehicles):
total_vehicle_count += 1
# print(total_vehicle_count)
return total_vehicle_count, dict_vehicle_count
def findObjects(ouputs, img):
hT, wT, cT = img.shape
bbox = []
classIds = []
confs = []
for output in outputs:
for det in output:
scores = det[5:]
classId = np.argmax(scores)
confidence = scores[classId]
if confidence > confThreshold:
w, h = int(det[2] * wT), int(det[3] * hT)
x, y = int((det[0] * wT) - w/2), int((det[1] * hT) - h/2)
bbox.append([x, y, w, h])
classIds.append(classId)
confs.append(float(confidence))
indices = cv2.dnn.NMSBoxes(bbox, confs, confThreshold, nmsThreshold)
for i in indices:
i = i[0]
box = bbox[i]
getVehicleCount(bbox, classNames[classIds[i]])
x, y, w, h = box[0], box[1], box[2], box[3]
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,255), 1)
cv2.putText(img, f'{classNames[classIds[i]].upper()} {int(confs[i]*100)}%', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,0,255), 2)
while True:
success, img = cap.read()
blob = cv2.dnn.blobFromImage(img, 1/255, (whT,whT), [0,0,0], 1, crop=False)
net.setInput(blob)
layerNames = net.getLayerNames()
outputnames = [layerNames[i[0]-1] for i in net.getUnconnectedOutLayers()]
# print(outputnames)
outputs = net.forward(outputnames)
findObjects(outputs, img)
cv2.imshow('Image', img)
if cv2.waitKey(1) & 0XFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
使用此代码,根据大小,有时会计算 1 辆车最多 50 次,这是非常不准确的。你能告诉我如何创建一个投资回报率,这样当检测到的车辆通过那个点时,这将是唯一一次计数。太感谢了。
解决方案
首先,我建议您考虑使用视觉跟踪器来跟踪每个检测到的矩形。即使您有一个 ROI 来裁剪靠近计数区域/线的图像,这也很重要。这是因为即使 ROI 已定位,检测仍可能会闪烁几次,从而导致计数错误。如果另一辆车可以进入 ROI 而第一辆车仍在通过它,则这一点尤其有效。
dlib
我建议使用广泛使用的库提供的易于使用的跟踪器。请参考这个例子来了解如何使用它。
您需要定义一条 ROI 线(在您的 ROI 内),而不是计算 ROI 内的检测。然后,跟踪检测每帧中的矩形中心。最后,一旦矩形中心通过 ROI 线,就增加计数器。
关于如何计算通过 ROI 线的矩形:
- 选择两个点来定义您的 ROI 线。
- 使用您的点找到一般线公式的参数
ax + by + c = 0
- 对于每一帧,在公式中插入矩形中心坐标并跟踪结果的符号。
- 如果结果的符号发生变化,则表示矩形中心已通过该线。
推荐阅读
- azure - Azure 机器学习(预览版)到客户洞察
- javascript - 通过滚动文本定位粘性循环
- postgresql - 使用 postgres 后端在 apache 超集上链接正则表达式替换
- c++ - Clang vs G++ 左值到右值转换
- java - Spring Boot 中的计数器
- linux - 用于从某个点(字符)替换文件名中的文本的重命名命令,但仅限于并保持文件扩展名
- android - 无法从 CoroutineScope 启动访问挂起 Dao 功能
- json - 如何在带有 swiftUI 列表的切换中使用 json 属性?
- java - 尝试使用 GSON API 读取 json 时出现空指针异常
- rust - 处理 macro_rules 中的可选模式