Python中通常使用管道、队列和共享内存等方式进行多进程之间的通信,但是前两者的速度堪忧,无法进行高速数据传递,C数据类型的共享内存则可以很好的解决这个问题。
关键在于
frame = frame.flatten(order='C')
temp = np.frombuffer(self.arr, dtype=np.uint8)
temp[:] = frame
完整代码
以下为图像采集进程代码
# -*- coding: utf-8 -*-
# @Time : 2021/9/11 18:48
# @Author : 67689e4f
# @Email : 964342226@qq.com
# @File : camera.py
import ctypes
import cv2
from multiprocessing import Process,sharedctypes
import time
import numpy as np
class Camera_p(Process):
def __init__(self, arr, isGrab):
super(Camera_p, self).__init__()
self.arr = arr
self.isGrab = isGrab
def run(self):
cap = cv2.VideoCapture(0)
while self.isGrab.value:
_, frame = cap.read()
cv2.waitKey(1)
frame = frame.flatten(order='C')
# frame = np.reshape(frame, (640*480*3, 1))
# frame_send = np.recarray(shape=(1,640*480*3), dtype=ctypes.c_int8, buf=self.arr)
# np.copyto(frame_send, frame) # 需要0.5秒,不理想
t_0 = time.time()
temp = np.frombuffer(self.arr, dtype=np.uint8)
temp[:] = frame
# self.arr[:] = frame #需要0.1秒
t_1 = time.time()
print(t_1 - t_0)
以下是显示进程代码,通常可以改为检测或者其他处理进程
import numpy as np
from multiprocessing import Process, Value, Array, sharedctypes
import ctypes
from camera import Camera_p
import cv2
class Show_window():
def __init__(self):
self.camera_arr = sharedctypes.RawArray(ctypes.c_int8, 640*480*3)
self.isGrab = Value('i', True)
def showpic(self):
cam_pro = Camera_p(self.camera_arr, self.isGrab)
cam_pro.start()
while True:
frame_show = np.frombuffer(self.camera_arr, dtype=np.uint8).reshape(480, 640, 3)
# frame_show = np.array(bytearray(self.camera_arr)).reshape(480, 640, 3)
cv2.imshow('0', frame_show)
key = cv2.waitKey(50)
if key == ord('q'):
self.isGrab.value = False
break
def main():
show = Show_window()
show.showpic()
if __name__ == '__main__':
main()