一文看懂所有图像与numpy矩阵(三维、四维均包含)之间的相互转换

一文看懂所有图像与numpy矩阵(三维、四维均包含)之间的相互转换,第1张

图像与numpy矩阵之间的相互转换:

1.RGB–>灰度图:

from PIL import Image
# 加载RGB图片
I = Image.open('/home/timg.jpg')
I.show()
# 转换为灰度图片
L = I.convert('L')
L.show()
L.save('/home/timg2.jpg')

2.图片–>numpy格式:

from PIL import Image
import numpy
# 加载图片
I = Image.open('/home/timg.jpg')
# 转换成numpy矩阵
img = numpy.array(I)
print(img.shape)
print(img)

3.numpy–>图片:
转为rgb的convert里为’RGB‘
转为灰度图的convert里为‘ gray’

from PIL import Image
import numpy
I = Image.open('/home/timg.jpg')
img = numpy.array(I)
# 把numpy矩阵转换成图片
img_np = Image.fromarray(img.astype('uint8')).convert('RGB')
img_np .show()

4.若numpy为四维的情况:
例如(520,256,256,3)表示520张256*256大小的三维图像,则需用循环将每一张图片提取出来再转化

# 保存路径
output_folder = 'output-te_data/'
for idx in range(520):
	#te_dataz为(520,256,256,3)的numpy矩阵
    im=Image.fromarray(np.uint8(te_data[idx])).convert('RGB')
    # 画图
    # plt.imshow(im)
    # plt.show()
    im.save(output_folder + 'sample_results_'+str(idx)+'.png')

5.若为(520,256,256,1)表示520张256*256大小的一维图像(灰度图像),则需用循环将每一张图片提取出来,将最后一维数据去掉,再保存:

# 保存路径
output_folder = 'output-te_mask/'
for idx in range(520):
	# 先将第三维去掉
    np_img = np.squeeze(te_mask[idx], axis=2)
    im=Image.fromarray(np.uint8(te_data[idx]))
    # 画图
    # plt.imshow(im,cmap='gray')
    # plt.show()
    im.save(output_folder + 'sample_results_'+str(idx)+'.png')

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/731839.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存