将RGB图像转换为LAB imag时出现意外输出

2024-04-19 09:33:00 发布

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

我正在尝试提取一个32位RGB图像的实验室a通道。然而,我没有正确地阅读图像,我得到了意想不到的结果。在

import cv2
org = cv2.imread('42.png', -1)
print org.dtype
# print uint8
lab_image = cv2.cvtColor(org, cv2.COLOR_RGB2LAB)
l,a,b = cv2.split(lab_image)
cv2.imshow('', a)
cv2.waitKey(0)

原始图像: http://labtools.ipk-gatersleben.de/images/42.png

预期输出(ImageJ): http://labtools.ipk-gatersleben.de/images/imagej_out.png

OpenCV输出: http://labtools.ipk-gatersleben.de/images/python_out.png

我也试着用略读来读取/转换图像,但结果是一样的。。。在


Tags: org图像imagehttppnglabdergb
1条回答
网友
1楼 · 发布于 2024-04-19 09:33:00

您的代码有几个问题。首先,正如Miki正确指出的,你必须交换红色和蓝色频道。根据OpenCV documentation(重点我):

Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed)

然后需要将图像强制转换为float32(因为cv2.cvtColor不支持float64),并将其缩小以适合0..1范围:

In case of linear transformations, the range does not matter. But in case of a non-linear transformation, an input RGB image should be normalized to the proper value range to get the correct results, for example, for RGB → Lu*v* transformation. For example, if you have a 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will have the 0..255 value range instead of 0..1 assumed by the function. So, before calling cvtColor, you need first to scale the image down

cv2.cvtColor返回的a的值被约束为-127 <= a <= 127。为了提高可视化效果,可以通过从a中减去a.min()来拉伸对比度,并通过一个因子255./(a.max() - a.min())来调整结果值,以适应范围0..255。如果你这样做,你应该得到预期的结果。以下是完整代码:

import cv2
import numpy as np
org = np.float32(cv2.imread('42.png', -1))/255.
lab_image = cv2.cvtColor(org, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab_image)
a_scaled = np.uint8(255.*(a - a.min())/(a.max() - a.min()))
cv2.imshow('', a_scaled)
cv2.waitKey(0)

奖金

您可以使用scikit image获得相同的结果:

^{pr2}$

a-channel

†实际上,OpenCV和scikit image的结果并不完全相同。由于与浮点运算相关的数值错误,两者略有不同。这种差异源于cv2.cvtColor返回三个float32的二维数组,而skimage.color.rgb2lab则生成一个float64的3D数组。在

相关问题 更多 >