Я пытаюсь использовать caffe и python для классификации изображений в режиме реального времени. Я использую OpenCV для потоковой передачи с веб-камеры в одном процессе и в отдельном процессе, используя caffe для выполнения классификации изображений на фреймах, вытащенных из веб-камеры. Затем я передаю результат классификации обратно в основной поток, чтобы заголовок потока веб-камеры.
Проблема в том, что, хотя у меня есть графический процессор NVIDIA и я выполняю предсказания caffe на графическом процессоре, основной поток отключается. Обычно без каких-либо прогнозов поток веб-камеры работает со скоростью 30 кадров в секунду; однако с прогнозами мой поток веб-камеры достигает в лучшем случае 15 кадров в секунду.
Я проверил, что кофе действительно использует GPU при выполнении предсказаний и что моя память GPU или GPU не максимизируется. Я также подтвердил, что мои ядра процессора не получают максимальную отдачу в любой момент во время программы. Мне интересно, не делаю ли я что-то не так, или если нет способа, чтобы эти 2 процесса действительно были отделены друг от друга. Любые советы приветствуются. Вот мой код для справки
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
caffe.set_mode_gpu()
caffe.set_device(0)
#Load caffe net -- code omitted
while True:
image = self.task_queue.get()
#crop image -- code omitted
text = net.predict(image)
self.result_queue.put(text)
return
import cv2
import caffe
import multiprocessing
import Queue
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
frame_copy[:] = frame
task_empty = True
while rval:
if task_empty:
tasks.put(frame_copy)
task_empty = False
if not results.empty():
text = results.get()
#Add text to frame
cv2.putText(frame,text)
task_empty = True
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
frame_copy[:] = frame
#Getting keyboard input
key = cv2.waitKey(1)
#exit on ESC
if key == 27:
break
Я уверен, что предсказание caffe замедляет все, потому что, когда я комментирую предсказание и передаю фиктивный текст взад и вперед между процессами, я снова получаю 30 кадров в секунду.
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
caffe.set_mode_gpu()
caffe.set_device(0)
#Load caffe net -- code omitted
while True:
image = self.task_queue.get()
#crop image -- code omitted
#text = net.predict(image)
text = "dummy text"
self.result_queue.put(text)
return
import cv2
import caffe
import multiprocessing
import Queue
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
frame_copy[:] = frame
task_empty = True
while rval:
if task_empty:
tasks.put(frame_copy)
task_empty = False
if not results.empty():
text = results.get()
#Add text to frame
cv2.putText(frame,text)
task_empty = True
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
frame_copy[:] = frame
#Getting keyboard input
key = cv2.waitKey(1)
#exit on ESC
if key == 27:
break