Numpy:numpy与image互转(np.array/np.asarray,Image.fromarray)
1np.array()将数据转化为矩阵array。默认情况下,将会copy该对象。numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)2 Image.fromarray()实现array到image的转换。PIL.Image.fromarray(obj, mode=None)参数描述返回值objObj
·
1 np.array()
将数据转化为矩阵array。默认情况下,将会copy该对象。
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
2 Image.fromarray()
实现array到image的转换。
PIL.Image.fromarray(obj, mode=None)
| 参数 | 描述 | 返回值 |
| obj | Object with array interface | An image object |
| mode | Mode to use (will be determined from type if None) See: Modes. |
需要注意的是,如果出现read-only错误,并不是转换的错误,一般是你读取的图片的时候,默认选择的是"r","rb"模式有关。
修正的办法: 手动修改图片的读取状态:
img.flags.writeable = True # 将数组改为读写模式
3 numpy与image互转
-
PIL image转换成array
import numpy as np
img = np.array(image)
或
img = np.asarray(image)
-
array转换成image
from PIL import Image
Image.fromarray(np.uint8(img))
4 栗子
from PIL import Image
import numpy as np
im = Image.open("a.jpg")
im.show()
img = np.array(im) # image类 转 numpy
img = img[:,:,0] #第1通道
im=Image.fromarray(img) # numpy 转 image类
im.show()
参考:
更多推荐



所有评论(0)