[英]How can I save a image converted from Grayscale to RGB in Python?
我是使用Python的新手,我想知道如何保存添加了额外香奈儿图像的图像。
我导入打开一个图像,并添加2通道的零数组来尝试转换为RBG图像,但是我通常不会保存,所以我不知道。
from PIL import Image
import numpy as np
from array import array
i= Image.open('/content/drive/My Drive/DDICM19/imagens/mdb001.jpg')
dim = np.zeros((1024,1024))
R = np.stack((i,dim, dim), axis=2)
dim = np.zeros((1024,1024))
dim.save('/content/drive/My Drive/DDICM19/imagensP/teste.jpg')
它返回:
AttributeError Traceback (most recent call last)
<ipython-input-32-073545b24d75> in <module>()
7 R = np.stack((i,dim, dim), axis=2)
8 dim = np.zeros((1024,1024))
----> 9 dim.save('/content/drive/My Drive/DDICM19/imagensP/teste.jpg')
AttributeError: 'numpy.ndarray' object has no attribute 'save'
有人帮忙。
首先:您尝试使用零div
保存numpy数组,而不使用RGB通道保存R
但是R
是numpy数组,您必须将其转换回PIL
图像
Image.fromarray(R, 'RGB').save('output.jpg')
要将灰度转换为RGB,最好对R,G,B重复相同的值,而不是添加零
R = np.stack((i, i, i), axis=2)
零值给我一些奇怪的东西。 它必须使用int8
或unit8
数据类型将其正确转换为RGB
dim = np.zeros((i.size[1], i.size[0]), 'uint8')
我还使用图像的大小来创建带有零的数组,但是您必须记住图像使用(x,y)
和数组使用(y, x)
,这意味着(row, column)
例
from PIL import Image
import numpy as np
i = Image.open('image.jpg')
#i = i.convert('L') # convert RGB to grayscale to have only one channel for tests
print(i.size) # (x, y)
dim = np.zeros((i.size[1], i.size[0]), 'int8') # array uses different order (y, x)
print(dim.shape)
R = np.stack((i, dim, dim), axis=2)
#R = np.stack((i, i, i), axis=2) # convert grayscale to RGB
print(R.shape)
#print(R[0,2]) # different values if not used `int8` #(y,x)
img = Image.fromarray(R, 'RGB')
img.save('output.jpg')
#print(img.getpixel((2,0))) # different values if not used `int8` #(x,y)
编辑:您还可以将零数组转换为灰度图像,可以用作图像中的通道
img_zero = Image.fromarray(dim, 'L')
img = Image.merge('RGB', (i, img_zero, img_zero))
img.save('output.jpg')
然后图像看起来很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.