用于多处理的Python OpenCV加速

时间:2018-11-10 16:24:26

标签: python

我正在尝试在网络摄像头的实时Feed上运行我的图像处理算法。 我希望它在多处理模块的并行进程中运行,我该如何实现呢? 这是我当前没有并行编码的代码:

from cv2 import VideoCapture , imshow , waitKey ,imwrite
import numpy as np
from time import time

def greenify (x):
    return some_value

skip = 4

video = VideoCapture(0)
video.set(3,640/skip)
video.set(4,480/skip)

total = 0
top_N = 100

while True:
    image = video.read()[1]        
    if waitKey(1) == 27:
        break

    arr = array([list(map(greenify,j)) for j in image])

    result = unravel_index(argpartition(arr,arr.size-top_N,axis=None)[-top_N:], arr.shape)
    centre = skip*np.median(result[0]) , skip*np.median(result[1])

    imshow('Feed', image)

print('Time taken:',total)
video.release()

1 个答案:

答案 0 :(得分:2)

基本上,我已经修改了您的代码,将其设置为一个函数,然后并行调用它。在代码中的任意位置调用bob.start(),并在几毫秒内调用并行代码即可

import numpy as np
from cv2 import VideoCapture

from multiprocessing import Process, Manager
import multiprocessing as mp

def getcors():
    skip = 4
    top_N = 100
    video = VideoCapture(0)
    video.set(3,640/skip)
    video.set(4,480/skip)
    while True:
        frame = video.read()[1]
        arr = np.array([list(map(greenify,j)) for j in frame])
        result = np.unravel_index(np.argpartition(arr,arr.size-top_N,axis=None)[-top_N:], arr.shape)
        centre = skip * np.median(result[1]) , skip*np.median(result[0])

bob = Process(target = getcors)