【问题标题】:Python OpenCV cannot display image correctly after transformationPython OpenCV 转换后无法正确显示图像
【发布时间】:2021-03-23 15:13:04
【问题描述】:

今天我正在尝试压缩下面的图像,在 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()

提前致谢。

【问题讨论】:

  • 确保您已将数据裁剪到 0 到 255 范围内并将其格式化为 8 位 (uint8)。
  • 确实,这似乎解决了问题。

标签: python image opencv compression pca


【解决方案1】:

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

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

approximated_uint8_image = cv2.convertScaleAbs(approximated_original_shape_image)

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多