推荐学习书目
› 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 · Aug 20, 2019 · 3472 views
    This topic created in 2592 days ago, the information mentioned may be changed or developed.
    with open('1.jpg', 'rb') as f:
          img = f.read()
    

    如何将 img 转成 numpy 数组呢?

    Supplement 1  ·  Aug 20, 2019
    这里是先用文件流把图片以二进制的形式读到内存里去,现在想做的是把这个内存数据转换成 numpy 数组
    8 replies  •  2019-08-21 11:27:36 +08:00
    Dustyposa
        1
    Dustyposa  
       Aug 20, 2019
    PIL can help you
    (pip install Pillow)
    epleone
        2
    epleone  
    OP
       Aug 20, 2019
    @Dustyposa
    通过 PIL 如何操作呢?
    angles6645
        3
    angles6645  
       Aug 20, 2019
    ```
    from PIL import Image
    import numpy as np
    img=np.array(Image.open('1.png'))
    ```
    epleone
        4
    epleone  
    OP
       Aug 20, 2019
    @zst Thx 不是从磁盘加载图片
    angles6645
        5
    angles6645  
       Aug 20, 2019 via Android
    @epleone 那可以用 StringIO 转换一下 read 得到的
    xuanhan863
        6
    xuanhan863  
       Aug 20, 2019
    help(np.frombuffer)
    epleone
        7
    epleone  
    OP
       Aug 21, 2019
    @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
       Aug 21, 2019
    @Dustyposa @zst @xuanhan863
    搞定了 图片通过 np.frombuffer 读进来 还没有解码 谢谢各位
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2496 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 04:12 · PVG 12:12 · LAX 21:12 · JFK 00:12
    ♥ Do have faith in what you're doing.