You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab中OpenCV展平图像后plt.imshow报错的解决方法

解决展平图像无法用plt.imshow显示的问题

错误原因

plt.imshow仅接受**2D数组(灰度图像)或3D数组(彩色图像)**作为输入,而flatten()会把图像数组转换成1D一维数组(形状如(61746,)),不符合图像数据的形状要求,因此触发TypeError。

两种正确的处理方式

方式1:还原为原图像形状显示

如果只是验证展平后的数据可以恢复成原图像,直接将展平数组reshape回原图像的尺寸即可:

# 替换原来错误的plt.imshow行
plt.subplot(2,3,4)
plt.title('Vertical_flattened (Reshaped) Image')
# 用原图像的形状reshape
vertical_reshaped = vertical_flattened.reshape(vertical.shape)
plt.imshow(vertical_reshaped, cmap='gray')

方式2:可视化一维像素序列

如果想直观展示展平后的一维像素值排列,可以把1D数组转为2D列向量(形状为(像素总数, 1)),并设置aspect='auto'调整显示比例:

plt.subplot(2,3,4)
plt.title('Vertical_flattened Pixel Sequence')
# 转成列向量并设置自适应比例
plt.imshow(vertical_flattened.reshape(-1, 1), cmap='gray', aspect='auto')

修改后的完整代码

import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
%matplotlib inline
import os

vertical = cv2.imread("vertical (1).PNG", cv2.IMREAD_GRAYSCALE)
horizontal = cv2.imread("horizontal (1).PNG", cv2.IMREAD_GRAYSCALE)
vertical = vertical/255   
horizontal = horizontal/255

print(vertical) 
print(horizontal) 

vertical_flattened = vertical.flatten() 
horizontal_flattened = horizontal.flatten()

print(vertical_flattened)
print(horizontal_flattened)

plt.rcParams["figure.figsize"]=(20,10)

plt.subplot(2,3,1)
plt.title('Vertical Image')
plt.imshow(vertical, cmap = 'gray')

# 方式1:还原为原图像形状显示
plt.subplot(2,3,4)
plt.title('Vertical_flattened (Reshaped) Image')
vertical_reshaped = vertical_flattened.reshape(vertical.shape)
plt.imshow(vertical_reshaped, cmap='gray')

plt.subplot(2,3,2)
plt.title('Horizontal Image')
plt.imshow(horizontal, cmap = 'gray')

# 可选:展示水平方向展平后的还原图像
plt.subplot(2,3,5)
plt.title('Horizontal_flattened (Reshaped) Image')
horizontal_reshaped = horizontal_flattened.reshape(horizontal.shape)
plt.imshow(horizontal_reshaped, cmap='gray')

plt.show()  # 替换cv2.waitKey(0),Colab中matplotlib用plt.show()更适配

内容的提问来源于stack exchange,提问作者Himexplore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:40:50