How to use OpenCV with GPU on Colab?

Viewed 1651

I am trying to make human detection using YOLOv4 on Colab. The code includes this lines:

import cv2

net =cv2.dnn.readNetFromDarknet(yolo_config_path,yolo_weights_path)

if cuda:
    net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

However, if I run this cell directly on Colab, I encounter an error like this:

Traceback (most recent call last):
  File "run_yolo.py", line 26, in <module>
    net =cv2.dnn.readNetFromDarknet(yolo_config_path,yolo_weights_path)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/dnn/src/darknet/darknet_io.cpp:554: error: (-212:Parsing error) Unsupported activation: mish in function 'ReadDarknetFromCfgStream'

I run this cell to avoid the error:

%cd /content
!git clone https://github.com/opencv/opencv
!git clone https://github.com/opencv/opencv_contrib
!mkdir /content/build
%cd /content/build
!cmake -DOPENCV_EXTRA_MODULES_PATH=/content/opencv_contrib/modules  -DBUILD_SHARED_LIBS=OFF  -DBUILD_TESTS=OFF  -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DWITH_OPENEXR=OFF -DWITH_CUDA=ON -DWITH_CUBLAS=ON -DWITH_CUDNN=ON -DOPENCV_DNN_CUDA=ON /content/opencv
!make -j8 install

When I write this line:

import cv2
cv2.__version__

The result is 4.5.1-dev.

But when I run the code, cv2 is OpenCV(4.1.2). How can I solve this problem?

1 Answers

Use the following version of opencv if you are going to use Yolov4 or other stuff:

!pip install opencv-contrib-python==3.4.13.47 --force-reinstall
Related