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()
结果如下: