Python灰度图像到RGB

2024-04-24 00:05:12 发布

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

我有一个灰度图像作为numpy数组,具有以下属性

shape = ( 3524, 3022), dtype = float32, min = 0.0, max = 1068.16

绘制为plt.imshow( gray, cmap = 'gray, vmin = 0, vmax = 80)的灰色图像如下所示

enter image description here

我想把它转换成RGB。我尝试了几种方法,例如np.stack、cv2.merge、cv2.color创建一个三维np.zeros图像,并将灰度图像分配给每个通道。当我绘制3D图像时,我得到的图像非常模糊,根本看不到“斑点”。我还尝试将其范围转换为[0,1]或[0,255]范围,但无效

使用np.stackplt.imshow( np.stack(( new,)*3, axis = 2)),我得到了这个

enter image description here

我该怎么办?提前谢谢


Tags: 图像numpy属性stacknp绘制数组min
2条回答

规范化图像的一种方法是使用cv2.normalizewithnorm_type=cv2.norm_MINMAX。它会将数据拉伸或压缩到0到255的范围(使用alpha和beta参数),并另存为8位类型

# normalize
norm = cv2.normalize(gray, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
print(norm.shape, norm.dtype)

# convert to 3 channel
norm = cv2.cvtColor(norm, cv2.COLOR_GRAY2BGR)
print(norm.shape, norm.dtype)
print(np.amin(norm),np.amax(norm))

通过将vmin=0,vmax=80传递给plt.imshow,基本上可以剪辑图像并重新缩放。所以你可以这样做:

gray_normalized = gray.clip(0,80)/80 * 255

# stack:
rgb = np.stack([gray_normalized]*3, axis=2)

cv2.imwrite('output.png', gray_normalized)

相关问题 更多 >