Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在OpenCV中设置ROI_Python_Opencv_Yolo - Fatal编程技术网

Python 在OpenCV中设置ROI

Python 在OpenCV中设置ROI,python,opencv,yolo,Python,Opencv,Yolo,我对OpenCV和Python非常陌生。我已经按照教程使用了Yolov3Tiny。它可以很好地检测车辆。但我需要完成的是计算通过特定车道的车辆数量。如果我使用检测到车辆(显示边界框)的方法进行计数,计数会变得非常不准确,因为边界框一直闪烁(这意味着它会再次定位同一车辆,有时最多5次),因此这不是一种好的计数方法。所以我想,如果我只算一辆车,如果它到达某个点,怎么样。我已经看到了很多代码,似乎使这一点,但由于我是一个初学者,它真的很难让我理解,更不用说,在我的系统中运行它。他们的示例需要安装太多的

我对OpenCV和Python非常陌生。我已经按照教程使用了Yolov3Tiny。它可以很好地检测车辆。但我需要完成的是计算通过特定车道的车辆数量。如果我使用检测到车辆(显示边界框)的方法进行计数,计数会变得非常不准确,因为边界框一直闪烁(这意味着它会再次定位同一车辆,有时最多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被定位,检测仍可能闪烁几次,导致计数错误。如果另一辆车可以进入ROI,而第一辆车仍在通过时,这一点尤其有效

我建议使用广泛使用的
dlib
库提供的易于使用的跟踪器。关于如何使用它,请参考本手册

您需要定义一条ROI线(在您的ROI内),而不是计算ROI内的检测数。然后,跟踪检测矩形以每帧为中心。最后,一旦矩形中心通过ROI线,增加计数器

关于如何计算通过ROI线的矩形:

  • 选择两个点来定义您的ROI线
  • 使用您的点查找通用直线公式的参数
    ax+by+c=0
  • 对于每个帧,在公式中插入矩形中心坐标,并跟踪结果的符号
  • 如果结果的符号改变,则表示矩形中心已通过该线

  • 如果你只看一个点或一个区域,它是否真的可靠,这是一个很高的推测。但是,您可以通过切片图像阵列创建自己的ROI,并将切片后的阵列传递到检测器中。