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学习笔记(深度学习)
笔记·python·学习
巴里巴气4 分钟前
安装GPU版本的Pytorch
人工智能·pytorch·python
wt_cs25 分钟前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python
_WndProc1 小时前
【Python】Flask网页
开发语言·python·flask
互联网搬砖老肖1 小时前
Python 中如何使用 Conda 管理版本和创建 Django 项目
python·django·conda
测试者家园1 小时前
基于DeepSeek和crewAI构建测试用例脚本生成器
人工智能·python·测试用例·智能体·智能化测试·crewai
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
大模型真好玩1 小时前
准确率飙升!Graph RAG如何利用知识图谱提升RAG答案质量(四)——微软GraphRAG代码实战
人工智能·python·mcp
前端付豪1 小时前
11、打造自己的 CLI 工具:从命令行到桌面效率神器
后端·python
前端付豪1 小时前
12、用类写出更可控、更易扩展的爬虫框架🕷
后端·python