skimage.color模块小坑:rgb2gray

skimage.color模块小坑:rgb2gray

问题记录

skimage.color模块中的rgb2gray可以将彩色图像变成灰度图。但是我今天的代码缺除了错误,读入彩色图输出灰度图像全是 0。问题代码如下

from PIL import Image
from skimage import color
import numpy as np

def path_to_gray(path: str) -> Image.Image:
    """
    Load an image from the given path and convert it to Gray format.
    """
    image = Image.open(path)
    if image.mode == "RGB":
        image = color.rgb2gray(image)
    elif image.mode != 'L':
        raise ValueError(f"Only RGB and Gray images are supported, not {image.mode}")
    return Image.fromarray(np.array(image).astype(np.uint8))

经过排查后,原来skimage.color.rgb2gray默认输出的是 0-1 范围的图像,而skimage.color. gray2rgb 输出的范围是 0-255。

改好的代码

下面是两幅图片,分别是彩色图的可见光图像和灰度图的红外图像:

  • 彩色图的可见光图像:/Volumes/Charles/DateSets/Fusion/RoadScene/vis_rgb/FLIR_00233.png
    在这里插入图片描述

  • 灰度图的红外图像:/Volumes/Charles/DateSets/Fusion/Toy/ir/16.png
    在这里插入图片描述
    下面我要写两个函数,可以分别把任意彩色或灰度图像,分别打开成任意彩色或灰度的样式。

# color.py
from PIL import Image
from skimage import color
import numpy as np

__all__ = [
    'path_to_gray',
    'path_to_rgb'
]

def path_to_gray(path: str) -> Image.Image:
    """
    Load an image from the given path and convert it to Gray format.
    """
    image = np.array(Image.open(path))
    if len(image.shape) == 3:
        image = color.rgb2gray(image)*255.0
    return Image.fromarray(image.astype(np.uint8))


def path_to_rgb(path: str) -> Image.Image:
    """
    Load an image from the given path and convert it to RGB format.
    """
    image = np.array(Image.open(path))
    if len(image.shape) == 2:
        image = color.gray2rgb(image)
    return Image.fromarray(image.astype(np.uint8))
# 调用的代码
a = path_to_rgb("/Volumes/Charles/DateSets/Fusion/RoadScene/ir/FLIR_00006.png")
b = path_to_rgb("/Volumes/Charles/DateSets/Fusion/RoadScene/vis_rgb/FLIR_00233.png")
c = path_to_gray("/Volumes/Charles/DateSets/Fusion/RoadScene/ir/FLIR_00006.png")
d = path_to_gray("/Volumes/Charles/DateSets/Fusion/RoadScene/vis_rgb/FLIR_00233.png")
[a,b,c,d] = [np.array(i) for i in [a,b,c,d]]

plt.subplot(2,2,1)
plt.imshow(a)
plt.title(f"Gray as RGB ([10,10]={a[10,10]})")
plt.subplot(2,2,2)
plt.imshow(b)
plt.title(f"RGB as RGB ([10,10]={b[10,10]})")
plt.subplot(2,2,3)
plt.imshow(c,cmap='gray')
plt.title(f"Gray as Gray ([10,10]={c[10,10]})")
plt.subplot(2,2,4)
plt.imshow(d,cmap='gray')
plt.title(f"RGB as Gray ([10,10]={d[10,10]})")
plt.show()

结果如下:
在这里插入图片描述

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值