python - 如何在 Python Linux 中使用内存映射文件

标签 python image frames

正如我在 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'

最佳答案

首先,我找到了一个可能有效的示例,但它使用了 tagName(客户端和服务器相同),这意味着它仅适用于 Window:

python-mmap-ipc


接下来我找到了适用于 Linux 的代码:

Sharing Python data between processes using mmap .

它在磁盘上创建真实文件,将其大小调整为图像大小,然后在 mmap()

中使用其 fd

我使用网络摄像头进行测试。

服务器

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(无需在磁盘上创建文件)可能可以与线程(或 fork )一起工作,因为它们共享相同的内存。

关于python - 如何在 Python Linux 中使用内存映射文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63553692/

相关文章:

html - 如何为网站创建分辨率可缩放箭头

javascript - HTML 页面中图像的最早预加载

html - 如何重用网页的一部分(使用 div)?

java - 按下键时改变球的方向

python - 如果不是 unicode 则解码

python - 在 OpenCv、Python 中保存相同图像时无法获得与原始图像相同的颜色

python - 处理大量数据而无需等待 block 完成

python - 如何用python创建透明的径向渐变?

firefox - 在 Firefox 中禁用框架调整大小

python - 如何返回 Flex 中 token 的最短匹配?