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

Python OpenCV在转换后无法正确显示图像,python,image,opencv,compression,pca,Python,Image,Opencv,Compression,Pca,今天我试着用Python中sklearn的PCA算法压缩下面的图像 因为图像是RGB(3个通道),所以我首先重塑了图像,使其成为2D。然后,在数据上应用PCA算法对图像进行压缩。在图像被压缩后,我对PCA变换进行反转,并将近似(解压缩)的图像重塑回其原始形状 然而,当我试图显示近似的图像时,我在这里得到了一个奇怪的结果: 当使用cv2.imwrite功能正确存储图像时,OpenCV无法使用cv2.imshow正确显示图像。你知道为什么会这样吗 我的代码如下: from sklearn.dec

今天我试着用Python中sklearn的PCA算法压缩下面的图像

因为图像是RGB(3个通道),所以我首先重塑了图像,使其成为2D。然后,在数据上应用PCA算法对图像进行压缩。在图像被压缩后,我对PCA变换进行反转,并将近似(解压缩)的图像重塑回其原始形状

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

当使用
cv2.imwrite
功能正确存储图像时,OpenCV无法使用
cv2.imshow
正确显示图像。你知道为什么会这样吗

我的代码如下:

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)

确保已将数据剪裁到0到255之间,并将其格式化为8位(uint8)。事实上,这似乎解决了问题。