gpt4 book ai didi

python - 如何使用 misc.imread 将图像切片为红色、绿色和蓝色 channel

转载 作者:太空狗 更新时间:2023-10-29 21:20:41 25 4
gpt4 key购买 nike

我正在尝试将图像分割成 RGB,但在绘制这些图像时遇到了问题。我使用此功能从某个文件夹获取所有图像:

def get_images(path, image_type):
image_list = []
for filename in glob.glob(path + '/*'+ image_type):
im=misc.imread(filename, mode='RGB')
image_list.append(im)
return image_list

此函数创建 4d 数组 (30, 1536, 2048, 3),我非常确定第一个值代表图像数量,第二和第三个是维度,第三个是 RGB 值。

在获取所有图像后,我将它们存储为一个 numpy 数组

image_list = get_images('C:\HDR\images', '.jpg')
temp = np.array(image_list)

之后我尝试使用简单的切片来从这些图像中获取特定的颜色:

red_images = temp[:,:,:,0]
green_images = temp[:,:,:,1]
blue_images = temp[:,:,:,2]

当我打印出这些值时,一切似乎都很好。

print(temp[11,125,311,:])
print(red_images[11,125,311])
print(green_images[11,125,311])
print(blue_images[11,125,311])

我得到以下信息:

[105  97  76]
105
97
76

到目前为止,一切似乎都很好,但是当我尝试显示图像时出现了问题。我使用 matplotlib.pyplot.imshow 来显示它,我得到的图像如下:

Image red channel

这是合理的,因为我选择红色:

 plt.imshow(temp[29,:,:,0])

但是当我将其更改为不同的颜色 channel 时,如下所示:

plt.imshow(temp[29,:,:,2])

我得到的图像是这样的:

Image bug channel

我的问题很简单。这里发生了什么?

最佳答案

我认为 matplotlib 只是将每个 channel (即强度)视为“热图”。

像这样将颜色映射传递给 imshow 函数,告诉它您希望它如何为图像着色:

plt.imshow(image_slice, cmap=plt.cm.gray)

编辑

@mrGreenBrown 回应您的评论,我假设您使用的 misc.imread 函数来自 scipy,即 scipy.misc.imread。该函数与 PIL 的函数没有什么不同。参见 scipy.misc.imread docs .感谢@dai 指出这一点。

任何图像的单个 channel 都只是强度。它没有颜色。对于以 RGB 颜色空间表示的图像,颜色是通过“混合”红色、绿色和蓝色的量(由相应 channel 的强度给出)获得的。 单一 channel 无法表达颜色

默认情况下,Matplotlib 将强度显示为热图,因此显示为“颜色”。

当您将单个 channel 保存为 JPEG 格式的图像时,该函数仅将单个 channel 复制 3 次,以便 R、G 和 B channel 都包含相同的强度。这是典型的行为,除非您将其保存为 PGM 等可以处理单 channel 灰度图像的格式。当您尝试将具有相同 channel 的此图像可视化 3 次时,由于每个像素的红色、绿色和蓝色贡献相同,因此图像显示为灰色。

plt.cm.gray 传递给 cmap 参数只是告诉 imshow 不要对强度进行“颜色编码”。因此,较亮的像素(接近白色的像素)意味着在这些位置有“更多”的“颜色”。

如果您想要颜色,您必须复制 3 channel 图像并将其他 channel 的值设置为 0

例如,将红色 channel 显示为“红色”:

# Assuming I is numpy array with 3 channels in RGB order
I_red = image.copy() # Duplicate image
I_red[:, :, 1] = 0 # Zero out contribution from green
I_red[:, :, 2] = 0 # Zero out contribution from blue

来自 stackoverflow 的一个相关问题 here .

关于python - 如何使用 misc.imread 将图像切片为红色、绿色和蓝色 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431599/

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