将1层图像转换为3层图像

时间:2019-01-17 22:28:06

标签: python numpy python-imaging-library

我正在尝试将1层(灰度)图像转换为3层RGB图像。下面是我正在使用的代码。这样可以正常运行,但不会产生正确的结果。

const it = {
  next: () => ({value: 1, done: false})
}

for (const val of it) {
  console.log(val)
}

我在这里做错了什么?我不希望有彩色图片,但是我希望黑白图片类似于输入内容。下面是输入和输出图像:

enter image description here enter image description here

3 个答案:

答案 0 :(得分:1)

根据图像的位深度,更改:

data = np.zeros((height, width, 3))

收件人:

data = np.zeros((height, width, 3), dtype=np.uint8)

对于8位图像,您需要将Numpy数组dtype强制为无符号的8位整数,否则默认为float64。对于16位,请使用np.uint16等。

答案 1 :(得分:0)

您的任务是什么?黑白图像或RGB彩色图像。如果要将灰色图像转换为黑白图像。您可以将图像直接转换为二进制图像。至于您的代码,您需要注意两件事。首先,像素的位置正确,错误的位置会使图像像帖子一样全黑。其次,您只能直接将RGB转换为灰度图像,而不能将其直接转换为RGB,因为它可能不准确。

答案 2 :(得分:0)

您可以使用PIL.ImagePIL.ImageOps进行操作,如下所示。由于它的编写方式,因此不需要将源图像设为一层-必要时,它将在使用之前将其转换为一层:

from PIL import Image
from PIL.ImageOps import grayscale

def convertLToRgb(src):
    src.load()   
    band = src if Image.getmodebands(src.mode) == 1 else grayscale(src)
    return Image.merge('RGB', (band, band, band))

src = 'whale_tail.png'
bw_img = Image.open(src)
rgb_img = convertLToRgb(bw_img)
rgb_img.show()