简体   繁体   English

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

[英]How can I save a image converted from Grayscale to RGB in Python?

I'm new to work with Python and I'd like if there is how to save a image that I added an additional chanel. 我是使用Python的新手,我想知道如何保存添加了额外香奈儿图像的图像。

I imported openned an image and added 2 chanels of array of zeros to try to transform to an RBG image, but the I coudn't savaet as I save usually. 我导入打开一个图像,并添加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')

It returned: 它返回:

    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'

Somebody help. 有人帮忙。

First: you try to save numpy array with zeros div , not R with RGB channels. 首先:您尝试使用零div保存numpy数组,而不使用RGB通道保存R


But R is numpy array and you have to convert it back to PIL image 但是R是numpy数组,您必须将其转换回PIL图像

Image.fromarray(R, 'RGB').save('output.jpg')

To convert grayscale to RGB better repeat the same values for R, G, B instead of adding zeros 要将灰度转换为RGB,最好对R,G,B重复相同的值,而不是添加零

R = np.stack((i, i, i), axis=2)

With zeros it gives me something strange. 零值给我一些奇怪的东西。 It has to uses int8 or unit8 data type to correctly convert it to RGB 它必须使用int8unit8数据类型将其正确转换为RGB

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

I also use size from image to create array with zeros but you have to remeber that image uses (x,y) and array use (y, x) which means (row, column) 我还使用图像的大小来创建带有零的数组,但是您必须记住图像使用(x,y)和数组使用(y, x) ,这意味着(row, column)


Example

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)

EDIT: You can also convert array of zeros to grayscale image which can be used as channel in image 编辑:您还可以将零数组转换为灰度图像,可以用作图像中的通道

 img_zero = Image.fromarray(dim, 'L')

 img = Image.merge('RGB', (i, img_zero, img_zero))
 img.save('output.jpg')

and then image looks interesting. 然后图像看起来很有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM