Skip to content

Instantly share code, notes, and snippets.

@applied-machinelearning
Last active November 1, 2019 16:04
Show Gist options
  • Save applied-machinelearning/9462e1368065fd7bf93334b0130a6ba0 to your computer and use it in GitHub Desktop.
Save applied-machinelearning/9462e1368065fd7bf93334b0130a6ba0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import cv2 as cv
import multiprocessing
def do_detection(backend, process_type):
print(f"Starting detection on {backend} from {process_type}")
net = cv.dnn.readNet(model="yolov3.weights", config="yolov3.cfg")
if backend == "CUDA":
net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
else:
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
image = cv.imread("lenna.png")
blob = cv.dnn.blobFromImage(image, 1 / 255, (416, 416), (0, 0, 0))
net.setInput(blob)
detections_blob = net.forward()
print(f"Results of detection on {backend} from {process_type}\n{detections_blob}\n\n")
def start_detection_multiprocess(backend):
process = multiprocessing.Process(target=do_detection, args=(backend, "multiprocessing"))
process.start()
process.join()
if __name__ == '__main__':
multiprocessing.set_start_method('spawn')
do_detection("CPU", "mainprocess")
do_detection("CUDA", "mainprocess")
start_detection_multiprocess("CPU")
start_detection_multiprocess("CUDA")
@antongisli
Copy link

nice. I got the cuda backend working without complaints in python, except it is slow (making me suspect it is not actually using it).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment