Convert rgb images in the form of numpy float64 to PIL images without loss

When converting an array of floating point type to an integer type, there may be a large gap in pixel values ​​due to type conversion. This is because rounding occurs when converting pixel values ​​from floating point types to integer types. If the original pixel value is less than 0 or greater than 255, truncation or overflow may occur, resulting in a large gap in pixel values.

In order to solve this problem, you can first normalize the pixel value of the floating point type to the range of 0 to 255, and then perform type conversion. This is done by multiplying the pixel value by 255 and rounding, then converting the result to an integer type.

The following is an example code that converts an array of type float64 to type uint8 and normalizes it to the range of 0 to 255:

import cv2
import numpy as np

# 读取图像并转换为RGB格式的NumPy数组
img = cv2.imread("example.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 将像素值归一化到0到255的范围内
img_norm = np.round(img / np.max(img) * 255)

# 将float64类型的数组转换为uint8类型
img_uint8 = img_norm.astype(np.uint8)

# 打印数组的形状和数据类型
print("Shape:", img_uint8.shape)
print("Data type:", img_uint8.dtype)

In the above code, we first use the cv2.imread() and cv2.cvtColor() functions to read and convert the image into a NumPy array in RGB format. We then normalize the pixel values ​​to the range of 0 to 255 and then use the astype() method to convert the data type of the array to uint8 type. Finally, we use the shape and dtype properties to print the shape and data type of the array respectively.

After this processing, you should be able to get an image array with a small difference in pixel values.

Guess you like

Origin blog.csdn.net/qq_60943902/article/details/129349095