V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
epleone
V2EX  ›  Python

求教,如何将内存数据转成 numpy 数组

  •  
  •   epleone · 2019-08-20 17:05:27 +08:00 · 2256 次点击
    这是一个创建于 1704 天前的主题,其中的信息可能已经有所发展或是发生改变。
    with open('1.jpg', 'rb') as f:
          img = f.read()
    

    如何将 img 转成 numpy 数组呢?

    第 1 条附言  ·  2019-08-20 17:40:21 +08:00
    这里是先用文件流把图片以二进制的形式读到内存里去,现在想做的是把这个内存数据转换成 numpy 数组
    8 条回复    2019-08-21 11:27:36 +08:00
    Dustyposa
        1
    Dustyposa  
       2019-08-20 17:12:39 +08:00
    PIL can help you
    (pip install Pillow)
    epleone
        2
    epleone  
    OP
       2019-08-20 17:36:35 +08:00
    @Dustyposa
    通过 PIL 如何操作呢?
    zst
        3
    zst  
       2019-08-20 18:20:57 +08:00
    ```
    from PIL import Image
    import numpy as np
    img=np.array(Image.open('1.png'))
    ```
    epleone
        4
    epleone  
    OP
       2019-08-20 18:53:01 +08:00
    @zst Thx 不是从磁盘加载图片
    zst
        5
    zst  
       2019-08-20 19:32:37 +08:00 via Android
    @epleone 那可以用 StringIO 转换一下 read 得到的
    xuanhan863
        6
    xuanhan863  
       2019-08-20 19:38:11 +08:00
    help(np.frombuffer)
    epleone
        7
    epleone  
    OP
       2019-08-21 10:48:42 +08:00
    @zst @xuanhan863
    谢谢两位
    一张(480, 640, 3)的彩色图片,
    我这么做可以读到图片
    ```python
    im = np.array(Image.open(BytesIO(buffer)))
    ```

    但是使用 np.frombuffer 读不进来,这是为啥啊 ,感觉使用 np.frombuffer 会更优雅一些。
    ``` python
    img = np.frombuffer(buffer, dtype=np.uint8)
    img.reshape(480, 640, 3)
    # 结果和上面一样
    # img = np.frombuffer(buffer, dtype=np.uint8, count=480*640*3)
    ```
    错误提示是
    ValueError: cannot reshape array of size 44263 into shape (480,640,3)
    epleone
        8
    epleone  
    OP
       2019-08-21 11:27:36 +08:00
    @Dustyposa @zst @xuanhan863
    搞定了 图片通过 np.frombuffer 读进来 还没有解码 谢谢各位
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1073 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:43 · PVG 02:43 · LAX 11:43 · JFK 14:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.