archive2020

Running YOLOv4 with the OpenCV DNN module on a CPU

How to run YOLOv4 and YOLOv4-tiny with OpenCV 4.4 in Python, without Darknet or a GPU, how I pick input size and thresholds, and when this is too slow.

4 min read#computer-vision#opencv#yolo

I want to know when a person is in front of my door camera, without sending video to a cloud service. I do not have a GPU in the house, so I tried the CPU path.

YOLOv4 was released in April 2020 by Alexey Bochkovskiy and co-authors (paper, code). OpenCV 4.4.0, released in July, lists YOLOv4 support in its DNN module (release notes). So the original Darknet weights run from Python with only opencv-python and numpy. No Darknet build, no PyTorch, no GPU.

This fits if you want the 80 COCO classes (person, car, dog and so on) without training, on a normal CPU, and a few frames per second is enough. It does not fit for real-time detection on many streams, or the full model on a Raspberry Pi.

Why not YOLOv5

In June 2020 a different team (Ultralytics) published a repository called YOLOv5, in PyTorch. There is no paper for it, and there was public discussion about the name and about how its benchmarks were measured (Roboflow’s summary). It moves fast. I picked YOLOv4 because it has a paper, stable weights, and direct support in OpenCV.

Install

python3 -m venv .venv && . .venv/bin/activate
pip install opencv-python==4.4.0.42 numpy
python -c "import cv2; print(cv2.__version__)"   # 4.4.0

From the Darknet repository you need coco.names (the 80 class names) and one model: yolov4.cfg with yolov4.weights (about 245 MB), or yolov4-tiny.cfg with yolov4-tiny.weights (much faster, less accurate). Keep the pairs together. A cfg from one model with weights from another loads without error and gives garbage boxes. Ask me how I know.

Versions of OpenCV before 4.4 may fail to load yolov4.cfg, because of the new Mish activation. Check cv2.__version__ first.

The code

cv2.dnn_DetectionModel does the pre-processing and the box decoding.

import cv2

CFG, WEIGHTS = "yolov4-tiny.cfg", "yolov4-tiny.weights"

with open("coco.names") as f:
    names = [line.strip() for line in f]

net = cv2.dnn.readNetFromDarknet(CFG, WEIGHTS)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

model = cv2.dnn_DetectionModel(net)
model.setInputParams(size=(416, 416), scale=1 / 255.0, swapRB=True)

frame = cv2.imread("street.jpg")
classes, scores, boxes = model.detect(frame, confThreshold=0.4, nmsThreshold=0.4)

for cls, score, box in zip(classes.flatten(), scores.flatten(), boxes):
    x, y, w, h = box
    label = f"{names[cls]} {score:.2f}"
    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
    cv2.putText(frame, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

cv2.imwrite("out.jpg", frame)

scale=1/255.0 turns pixel values 0..255 into 0..1, which Darknet models expect. swapRB=True converts OpenCV’s BGR to RGB. size must be a multiple of 32. nmsThreshold controls non-maximum suppression, which removes overlapping boxes for the same object.

If nothing is above the threshold, model.detect returns empty tuples, and .flatten() fails. Check for that first.

Measure on your machine

Speed depends a lot on the CPU and the input size, so I do not trust anyone else’s numbers here:

import time

for size in (320, 416, 608):
    model.setInputParams(size=(size, size), scale=1 / 255.0, swapRB=True)
    model.detect(frame, 0.4, 0.4)              # warm up
    t = time.perf_counter()
    for _ in range(10):
        model.detect(frame, 0.4, 0.4)
    print(size, f"{(time.perf_counter() - t) / 10 * 1000:.0f} ms")

net.getPerfProfile() also gives the time of the last inference.

Settings

Decision Start with Change when
Model yolov4-tiny Small or far objects are missed. Then try full yolov4
Input size 416 Small objects missed: go to 608. Too slow: go to 320
Confidence threshold 0.4 Too many false alarms: raise it. Missed objects: lower it
NMS threshold 0.4 Several boxes on one object: lower it

Change one thing at a time, and test on images from your real camera, not sample photos. Night, a window, or a camera mounted high all give very different results. Upscaling a small frame to 608 does not add detail either.

Reading from a camera

For an RTSP camera, read every frame but detect only on some:

cap = cv2.VideoCapture("rtsp://user:pass@192.168.1.50:554/stream1")
n = 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    n += 1
    if n % 10:          # detect on every 10th frame
        continue
    classes, scores, boxes = model.detect(frame, 0.4, 0.4)
    # ... act on the result ...

If detection is slower than the camera frame rate and you skip reads, the buffer in VideoCapture fills up and results lag behind real time. Reading every frame, like above, keeps the buffer empty. A cleaner way is to read frames in a separate thread and always process the newest one.

Before shipping anything with this, check the licenses of the weights and the code. Mine is only for home use.