python多进程共享变量,附共享图像内存实例
由于python多线程只能在单核上跑,因此需要cpu多核处理只能用多进程。
python多进程一般用multiprocessing。可是用multiprocessing的array或者value对内存的读写速度特别慢。原因以及解决方法如下链接:
http://stackoverflow.com/questions/37705974/why-are-multiprocessing-sharedctypes-assignments-so-slow
针对numpy的图像多进程共享的示例代码如下:
1 import numpy as np 2 import cv2, multiprocessing, sharedmem 3 4 def show_image(image_in): 5 while 1: 6 cv2.imshow("avi",image_in) 7 cv2.waitKey(1) 8 9 def aa(images): 10 while 1: 11 for i in range(20): 12 cv2.imshow("a",images[i]) 13 cv2.waitKey(1) 14 15 if __name__ == '__main__': 16 cap = cv2.VideoCapture('1.avi') 17 assert cap.isOpened(), 'Cannot capture source' 18 19 _, image = cap.read() 20 shape = np.shape(image) 21 dtype = image.dtype 22 images = multiprocessing.Manager().dict() 23 image_in = sharedmem.empty(shape, dtype) 24 image_in[:] = image.copy() 25 26 a = multiprocessing.Process(target=show_image,args=(image_in,)) 27 a.start() 28 count = 0 29 for i in range(20): 30 ret, image = cap.read() 31 if not ret: 32 break 33 image_in[:] = image.copy() 34 images[count] = image_in 35 count += 1 36 multiprocessing.Process(target=aa, args=(images,)).start() 37 aa.join()