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()
相关推荐
2501_9327502629 分钟前
Java IO流基础全面详解:字节流、字符流
java·开发语言
冰暮流星36 分钟前
javascript之默认事件
开发语言·javascript·ecmascript
fengci.38 分钟前
CTF+随机困难题目
android·开发语言·前端·学习·php
互联网时光机39 分钟前
我用 UniApp + 腾讯云 IAI 做了一个“明星脸比对“小程序,零后台延迟
经验分享·python·人脸识别
l1t41 分钟前
DeepSeek总结的Python 3.14.5 发布候选版本
开发语言·python
雪度娃娃1 小时前
设计模式——单例模式
开发语言·c++·设计模式
Cyber4K1 小时前
【Python专项】进阶语法-日志分类与分析(2)
开发语言·前端·python
lbb 小魔仙1 小时前
Python + LangChain 环境搭建完全指南:从零构建本地 RAG 知识库(附 Ollama 本地模型集成)
开发语言·python·langchain
风落无尘1 小时前
Python 包发布全流程:从项目结构到 PyPI 上线,以及我踩过的那些坑
开发语言·python·pip
xxjj998a1 小时前
PHP vs C#:两大编程语言终极对比
开发语言·c#·php