How to force cv2 to use second GPU in Python for dnn

I’m trying to get mobilenet detectors working on multiple cameras on my local network, with inference running on two GPUs. I searched around a bit and found out you can select a specific GPU using cv2.cuda.SetDevice(gpuid), but that didn’t work for me in OpenCV 4.5. Is this command deprecated/obsolete?


please explain “didn’t work”.

1 Like

It gave me an error saying the command didn’t exist, that SetDevice wasn’t a method for the cv2.cuda class.

Have you compiled OpenCV with CUDA?

I just tried


with no errors and when I tried device 1 which doesn’t exist I get the below error informing me of that

OpenCV(4.5.0) Error: Gpu API call (invalid device ordinal) in cv::cuda::setDevice, file modules\core\src\cuda_info.cpp, line 73
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.5.0) \modules\core\src\cuda_info.cpp:73: error: (-217:Gpu API call) invalid device ordinal in function 'cv::cuda::setDevice'
1 Like

I just reran the program with cv2.cuda.setDevice(1) instead of cv2.cuda.SetDevice(1), and it ran. I think the guide that I read had the capitalization wrong. Sorry for the dumb mistake. My best guess as to why device 1 didn’t work for you but worked for me is because you might not have a second GPU.

Also, I’m new, how do you insert blocks of code like you did?

three backticks for a block:

generic code here

python code here. try other languages too

single backticks for inline code

single backticks for `inline` code

or indent by 4 spaces for monospaced text without highlighting. toolbar above text entry box has a button for that.

1 Like