gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:26:03 25 4
gpt4 key购买 nike

我正在尝试将 1 层(灰度)图像转换为 3 层 RGB 图像。下面是我正在使用的代码。运行时没有错误,但不会创建正确的结果。

from PIL import Image  # used for loading images

def convertLToRgb(img):
height = img.size[1]
width = img.size[0]
size = img.size
mode = 'RGB'
data = np.zeros((height, width, 3))
for i in range(height):
for j in range(width):
pixel = img.getpixel((j, i))
data[i][j][0] = pixel
data[i][j][1] = pixel
data[i][j][2] = pixel
img = Image.frombuffer(mode, size, data)
return img

我在这里做错了什么?我不期待彩色图片,但我期待类似于输入的黑白图片。以下是输入和输出图像:

enter image description here enter image description here

最佳答案

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

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

至:

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

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

关于python - 将 1 层图像转换为 3 层图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com