Python OpenCV转换后无法正确显示图像

Python OpenCV cannot display image correctly after transformation

今天我在Python.

中使用sklearn的PCA算法尝试压缩下面的图像

因为图像是RGB(3通道),所以我先reshape图像,让它变成2D。然后,我对数据应用 PCA 算法来压缩图像。图像压缩后,我反转 PCA 变换并将近似(解压缩)图像重塑回其原始形状。

然而,当我尝试显示近似图像时,我得到了这个奇怪的结果:

虽然 图像使用 cv2.imwrite 函数正确存储,但 OpenCV 无法使用 [=] 正确显示图像 13=]。您知道为什么会这样吗?

我的代码如下:

from sklearn.decomposition import PCA
import cv2
import numpy as np

image_filepath = 'baby_yoda_image.jpg'

# Loading image from disk.
input_image = cv2.imread(image_filepath)
height = input_image.shape[0]
width = input_image.shape[1]
channels = input_image.shape[2]

# Reshaping image to perform PCA.
print('Input image shape:', input_image.shape)
#--- OUT: (533, 800, 3)

reshaped_image = np.reshape(input_image, (height, width*channels))
print('Reshaped Image:', reshaped_image.shape)
#--- OUT: (533, 2400)

# Applying PCA transformation to image. No whitening is applied to prevent further data loss.
n_components = 64
whitening = False
pca = PCA(n_components, whitening)
compressed_image = pca.fit_transform(reshaped_image)

print('PCA Compressed Image Shape:', compressed_image.shape)
#--- OUT: (533, 64)
print('Compression achieved:', np.around(np.sum(pca.explained_variance_ratio_), 2)*100, '%')
#--- OUT: 97.0 %    

# Plotting images.
approximated_image = pca.inverse_transform(compressed_image)
approximated_original_shape_image = np.reshape(approximated_image, (height, width, channels))

cv2.imshow('Input Image', input_image)
cv2.imshow('Compressed Image', approximated_original_shape_image)
cv2.waitKey()

提前致谢。

最后,我找到了解决这个问题的方法,感谢@fmw42。变换后,像素负值也有超过255的值。

幸运的是,OpenCV 确实用这行代码解决了这个问题:

approximated_uint8_image = cv2.convertScaleAbs(approximated_original_shape_image)