【发布时间】:2020-08-24 01:40:57
【问题描述】:
正如我在 Python 文档中看到的,
https://docs.python.org/3/library/mmap.html.
Linux 中的 Python 可以完全支持内存映射文件。然而,当我试图将这个想法应用到我的应用程序时。我无法运行示例。
我的应用程序是将帧从 Python 文件(客户端)发送到另一个 Python 文件(服务器)。
客户代码
import mmap
import time
import os
import cv2 as cv
print("Opening camera...")
cap = cv.VideoCapture('/home/hunglv/Downloads/IMG_8442.MOV')
mm = None
try:
while True:
ret, img = cap.read()
if not ret:
break
if mm is None:
mm = mmap.mmap(-1,img.size,mmap.MAP_SHARED, mmap.PROT_WRITE)
# write image
start = time.time()
buf = img.tobytes()
mm.seek(0)
mm.write(buf)
mm.flush()
stop = time.time()
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 as cv
import numpy as np
shape = (1080, 1920, 3)
n = np.prod(shape)
mm = mmap.mmap(-1, n)
while True:
# read image
print (mm)
start = time.perf_counter()
mm.seek(0)
buf = mm.read(12)
img = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
stop = time.perf_counter()
print("Reading Duration:", (stop - start) * 1000, "ms")
cv.imshow("img", img)
key = cv.waitKey(1) & 0xFF
key = chr(key)
if key.lower() == "q":
break
cv.destroyAllWindows()
mm.close()
在服务器端,我将内存索引设置为 0,并尝试从内存中读取字节。但是,似乎服务器无法正确读取来自客户端的数据。
[更新] 我试图在服务器端读出前 12 个字节。该值是恒定的,不再变化。
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
此外, 随机帧的前 12 个字节是
b'\xf5\xff\xff\xf0\xfa\xfe\xdf\xe9\xed\xd2\xdc\xe0'
【问题讨论】:
-
您收到什么错误?数据是否不正确或根本没有读取?
-
@rassar 我已将信息添加到帖子中。从内存中读取的数据是一样的。
-
对于我在
mmap()中使用-1,您创建了两个分开的mmaps,两个程序使用不同的mmap。您必须在mmaps中使用相同的fileno -
也许您应该使用
shared-memory或pipes到sockets从一个进程发送到另一个。 -
在文档中,-1 是匿名内存,我试过用另一个号码,但它说找不到号码。我认为这两个 Python 文件会创建不同的
mmaps(两个不同的对象)。这就是为什么服务器不理解客户端中的mmaps的原因。