import os,sys import gc import multiprocessing as mp import numpy as np import cv2 import time
def write(stack, cam, top: int) -> None: print('Process to write: %s' % os.getpid()) cap = cv2.VideoCapture(cam) while True: t = time.time() _, img = cap.read() if _: #print(type(img)) stack.append((t, img)) #print('inininininininin ........... ') # 每到一定容量清空一次缓冲栈 # 利用gc库,手动清理内存垃圾,防止内存溢出 if len(stack) >= top: del stack[::2] gc.collect()
def run(stack_1,stack_2,stack_4,stack_34) -> None: #提醒返回值是一个None print('Process to read: %s' % os.getpid()) while True: # print("正在读取第%d帧:" %index) frame=np.zeros((960,1280,3),dtype=np.uint8) if len(stack_4) >= 5 and len(stack_34) >= 5 and len(stack_1) >= 5 and len(stack_2) >= 5: #if len(stack_1) >= 5 and len(stack_2) >= 5: temp4 = stack_4.pop(0) temp34 = stack_34.pop(0) temp1 =stack_1.pop(0) temp2=stack_2.pop(0) frame_batch = [temp4[1], temp34[1],temp1[1],temp2[1]] #print(temp4[1].shape) frame4=cv2.resize(temp4[1],(int(640),int(480)),interpolation=cv2.INTER_CUBIC) frame34=cv2.resize(temp34[1],(int(640),int(480)),interpolation=cv2.INTER_CUBIC) frame1=cv2.resize(temp1[1],(int(640),int(480)),interpolation=cv2.INTER_CUBIC) frame2=cv2.resize(temp2[1],(int(640),int(480)),interpolation=cv2.INTER_CUBIC) #frame_up=np.hstack((frame1,frame2)) #frame_down=np.hstack((frame4,frame34)) #frame=np.hstack((frame_up,frame_down)) #cv2.imshow('video',temp4[1]) frame[0:480, 0:640, :] = frame4 frame[0:480, 640:1280, :] = frame34 frame[480:960, 0:640, :] = frame1 frame[480:960, 640:1280, :] = frame2 cv2.imshow('video',frame) cv2.waitKey(1) else: continue
if __name__ == '__main__': # 父进程创建缓冲栈,并传给各个子进程: #mp.set_start_method('spawn') q_1 = mp.Manager().list() q_2 = mp.Manager().list() q_4 = mp.Manager().list() q_34 = mp.Manager().list() pw_1 = mp.Process(target=write, args=(q_1, "填写地址", 100)) pw_2 = mp.Process(target=write, args=(q_2, "填写地址", 100)) pw_4 = mp.Process(target=write, args=(q_4, "填写地址", 100)) pw_34 = mp.Process(target=write, args=(q_34, "填写地址", 100)) #pr = mp.Process(target=run, args=(q_34,)) pr = mp.Process(target=run, args=(q_1,q_2,q_4,q_34,)) pw_1.start() pw_2.start() pw_4.start() pw_34.start() pr.start() pr.join()
pw_1.terminate() pw_2.terminate() pw_4.terminate() pw_34.terminate()