import gc
import os
from multiprocessing import Manager, Process
import cv2
video_address = r"F:\video\obama.mp4" # 这里原为海康威视RTSP地址,不过普通视频文件也存在溢出
# 向共享缓冲栈中写入数据:
def write(stack, cam, top: int) -> None:
print('Process to write: %s' % os.getpid())
cap = cv2.VideoCapture(cam)
while True:
success, img = cap.read()
if success:
stack.append(img)
# 每到一定容量清空一次缓冲栈
# 利用gc库,手动清理内存垃圾,防止内存溢出
print(len(stack))
if len(stack) >= top:
del stack[:]
gc.collect()
# 在缓冲栈中读取数据:
def read(stack) -> None: #提醒返回值是一个None
print('Process to read: %s' % os.getpid())
print("开始逐帧读取")
while True:
if len(stack) >= 10:
frame = stack.pop()
cv2.imshow("video", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
else:
continue
cv2.destroyAllWindows()
if __name__ == '__main__':
# 父进程创建缓冲栈,并传给各个子进程:
q = Manager().list()
pw = Process(target=write, args=(q, video_address, 100))
pr = Process(target=read, args=(q,))
pw.start()
pr.start()
pr.join()
pw.terminate()
import os
from multiprocessing import Manager, Process
import cv2
video_address = r"F:\video\obama.mp4" # 这里原为海康威视RTSP地址,不过普通视频文件也存在溢出
# 向共享缓冲栈中写入数据:
def write(stack, cam, top: int) -> None:
print('Process to write: %s' % os.getpid())
cap = cv2.VideoCapture(cam)
while True:
success, img = cap.read()
if success:
stack.append(img)
# 每到一定容量清空一次缓冲栈
# 利用gc库,手动清理内存垃圾,防止内存溢出
print(len(stack))
if len(stack) >= top:
del stack[:]
gc.collect()
# 在缓冲栈中读取数据:
def read(stack) -> None: #提醒返回值是一个None
print('Process to read: %s' % os.getpid())
print("开始逐帧读取")
while True:
if len(stack) >= 10:
frame = stack.pop()
cv2.imshow("video", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
else:
continue
cv2.destroyAllWindows()
if __name__ == '__main__':
# 父进程创建缓冲栈,并传给各个子进程:
q = Manager().list()
pw = Process(target=write, args=(q, video_address, 100))
pr = Process(target=read, args=(q,))
pw.start()
pr.start()
pr.join()
pw.terminate()


