Python 共享内存之 shared_memory

Python 共享内存之 shared_memory

示例通过共享内存读写图片

python 复制代码
from multiprocessing import  shared_memory
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# 随机颜色 RGBA
def random_color()->tuple:
    rgba = np.random.randint(0,255,size=4)
    return tuple(rgba)

# 用随机数填充像素
def fill_random_pixels(img):
    width, height = img.size
    for x in range(width):
        for y in range(height):
            img.putpixel((x, y), random_color())


if __name__ == "__main__":

    # 选择随机图片或者加载本地图片 
    random_image=False

    img_width = 100
    img_height = 100
    img = Image.new('RGBA', (img_width, img_height))

    if random_image:
        fill_random_pixels(img)
        origin_data = np.array(img)
    else:
        img_path = "C:\\Users\\mingxingwang\\Pictures\\qt-logo.png"
        # 打开图片并转换为numpy数组
        img = Image.open(img_path)
        origin_data = np.array(img)

    #------------- 数据写入共享内存

    # 创建共享内存对象
    shm_a = shared_memory.SharedMemory(create=True, name="my_share_mem",size=origin_data.nbytes)

    #构造关联共享内存的数组
    mem_array = np.ndarray(origin_data.shape, dtype=origin_data.dtype, buffer=shm_a.buf)

    #copy 数据到共享内存
    mem_array[:]=origin_data[:]

    print(f"------------mem_array------------:\n{mem_array}\n")

    #显示原始图片
    origin_image = Image.frombytes(mode='RGBA',size=img.size,data=origin_data)
    plt.imshow(origin_image)
    plt.show()

    #------------- 共享内存获取数据

    existing_shm = shared_memory.SharedMemory(name='my_share_mem')
    array_from_mem = np.ndarray(origin_data.shape, dtype=origin_data.dtype, buffer=existing_shm.buf)
    print(f"------------array_from_mem------------:\n{array_from_mem}\n")

    ##从共享内存构造图片
    img_from_mem = Image.frombytes(mode='RGBA',size=img.size,data=array_from_mem)
    
    ##显示从共享内存获取的图片
    plt.imshow(img_from_mem)
    plt.show()



    shm_a.close()
    shm_a.unlink()
相关推荐
树叶@1 分钟前
Python数据分析7
开发语言·python
wydaicls4 分钟前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地37 分钟前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹38 分钟前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
奇树谦42 分钟前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt
VBA63371 小时前
VBA之Word应用第三章第十节:文档Document对象的方法(三)
开发语言
老胖闲聊1 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点1 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI1 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
贩卖纯净水.2 小时前
浏览器兼容-polyfill-本地服务-优化
开发语言·前端·javascript