1 回答

TA貢獻1780條經驗 獲得超5個贊
首先,我找到了可能有效但它使用的示例tagName
(客戶端和服務器相同),這意味著它僅適用于 Window:
python-mmap-ipc
接下來我找到了適用于 Linux 的代碼:
使用 mmap 在進程之間共享 Python 數據。
它在磁盤上創建真實文件,將其大小調整為圖像大小,然后使用它的fd
inmmap()
我使用網絡攝像頭進行測試。
服務器
import mmap
import time
import os
import cv2
print("Opening camera...")
cap = cv2.VideoCapture(0)
#print(cap.get(cv.CAP_PROP_FRAME_WIDTH))? # 640
#print(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) # 480
shape = (480, 640, 3)
n = (480*640*3)
fd = os.open('/tmp/mmaptest', os.O_CREAT | os.O_TRUNC | os.O_RDWR)
#os.write(fd, b'\x00' * n)? # resize file
os.truncate(fd, n)? # resize file
mm = None
try:
? ? while True:
? ? ? ? ret, img = cap.read()
? ? ? ??
? ? ? ? if not ret:
? ? ? ? ? ? break
? ? ? ??
? ? ? ? if mm is None:
? ? ? ? ? ? mm = mmap.mmap(fd, n, mmap.MAP_SHARED, mmap.PROT_WRITE)? # it has to be only for writing
? ? ? ? # write image
? ? ? ? start = time.perf_counter()
? ? ? ??
? ? ? ? buf = img.tobytes()
? ? ? ? mm.seek(0)
? ? ? ? mm.write(buf)
? ? ? ? mm.flush()
? ? ? ??
? ? ? ? stop = time.perf_counter()
? ? ? ? print("Writing Duration:", (stop - start) * 1000, "ms")
except KeyboardInterrupt:
? ? pass
print("Closing resources")
cap.release()
mm.close()
客戶
import mmap
import time
import os
import cv2
import numpy as np
shape = (480, 640, 3)
n = (480*640*3)
fd = os.open('/tmp/mmaptest', os.O_RDONLY)
mm = mmap.mmap(fd, n, mmap.MAP_SHARED, mmap.PROT_READ)? # it has to be only for reading
while True:
? ? # read image
? ? start = time.perf_counter()
? ??
? ? mm.seek(0)
? ? buf = mm.read(n)
? ? img = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
? ??
? ? stop = time.perf_counter()
? ? print("Reading Duration:", (stop - start) * 1000, "ms")
? ? cv2.imshow("img", img)
? ? key = cv2.waitKey(1) & 0xFF
? ? key = chr(key)
? ? if key.lower() == "q":
? ? ? ? break
? ??
cv2.destroyAllWindows()
mm.close()
順便說一句:可能mmap()與-1(不在磁盤上創建文件)可以與線程(或分叉)一起工作,因為它們共享相同的內存。
添加回答
舉報