我应该如何将 float32 图像转换为 uint8 图像?

Ham*_*eza 4 python opencv image-processing

我想使用 openCV 库在 Python 中将图像转换为float32图像uint8。我使用了以下代码,但我不知道它是否正确。

Ifloat32图像。

J = I*255
J = J.astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

如果你能帮助我,我真的很感激。

Joh*_*318 10

如果您想将图像从单精度浮点(即FLOAT32)转换为UINT8,numpyopencv在python提供了两个方便的方法。

如果您知道您的图像范围在 0 到 255 或 0 到 1 之间,那么您可以简单地按照您已经做的方式进行转换:

I *= 255 # or any coefficient
I = I.astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

如果您不知道范围,我建议您应用最小最大标准化,即: (value - min) / (max - min)

使用 opencv,您只需调用以下指令:

I = cv2.normalize(I, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
Run Code Online (Sandbox Code Playgroud)

返回的变量 I 类型将具有类型np.uint8(由最后一个参数指定)和 0 到 255 之间的范围。

使用numpy你也可以写类似的东西:

def normalize8(I):
  mn = I.min()
  mx = I.max()

  mx -= mn

  I = ((I - mn)/mx) * 255
  return I.astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,astype 会截断小数。如果您需要更高的准确性,我建议将最后几行更改为 `I = ((I - mn)/mx) * 255.0` 和 `return np.round(I).astype(np.uint8)` (3认同)