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

2019-08-20 17:05:27 +08:00
 epleone
with open('1.jpg', 'rb') as f:
      img = f.read()

如何将 img 转成 numpy 数组呢?

2266 次点击
所在节点    Python
8 条回复
Dustyposa
2019-08-20 17:12:39 +08:00
PIL can help you
(pip install Pillow)
epleone
2019-08-20 17:36:35 +08:00
@Dustyposa
通过 PIL 如何操作呢?
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
2019-08-20 18:53:01 +08:00
@zst Thx 不是从磁盘加载图片
zst
2019-08-20 19:32:37 +08:00
@epleone 那可以用 StringIO 转换一下 read 得到的
xuanhan863
2019-08-20 19:38:11 +08:00
help(np.frombuffer)
epleone
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
2019-08-21 11:27:36 +08:00
@Dustyposa @zst @xuanhan863
搞定了 图片通过 np.frombuffer 读进来 还没有解码 谢谢各位

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/593564

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX