如何在Python中保存从灰度转换为RGB的图像?

2024-10-01 11:40:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我想知道如何保存我添加了一个额外chanel的图像。你知道吗

我导入了一个打开的图像,并添加了两个通道的零数组来尝试转换成一个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'

快来人帮忙。你知道吗


Tags: from图像imageimportnumpymysavenp
1条回答
网友
1楼 · 发布于 2024-10-01 11:40:37

首先:尝试用零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)

有了零,我就有点奇怪了。它必须使用int8unit8数据类型才能正确地将其转换为RGB

dim = np.zeros((i.size[1], i.size[0]), 'uint8')

我也使用size from image来创建带有零的数组,但是您必须记住,image使用(x,y),而array使用(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')

然后图像看起来很有趣。你知道吗

相关问题 更多 >