Matplotlib plt.imsave保存图片报错:tuple对象无shape属性
问题解决:plt.imsave保存图像报错AttributeError: 'tuple' object has no attribute 'shape'
问题场景
在Ubuntu 22.04.1 LTS系统、OpenCV 4.6.0环境下,Python代码可通过plt.imshow正常显示图像,但调用plt.imsave保存时失败,报错AttributeError: 'tuple' object has no attribute 'shape',预期保存plt.show已成功显示的图像。
相关代码片段
import numpy as np import glob import matplotlib.pyplot as plt import skimage.io import skimage.color import skimage.filters from PIL import Image import pytesseract import cv2 as cv import numpy as np # load the image image = skimage.io.imread("/home/joy/桌面/test_11_4/Img_after_sharpen.png") fig, ax = plt.subplots() plt.imshow(image) # convert the image to grayscale gray_image = skimage.color.rgb2gray(image) # blur the image to denoise blurred_image = skimage.filters.gaussian(gray_image, sigma=1.0) fig, ax = plt.subplots() plt.imshow(blurred_image, cmap="gray") # create a histogram of the blurred grayscale image histogram, bin_edges = np.histogram(blurred_image, bins=256, range=(0.0, 1.0)) fig, ax = plt.subplots() plt.plot(bin_edges[0:-1], histogram) plt.title("Grayscale Histogram") plt.xlabel("grayscale value") plt.ylabel("pixels") plt.xlim(0, 1.0) # create a mask based on the threshold t1 = 0.8 t2 = 0.05 binary_mask = blurred_image < t1 fig, ax = plt.subplots() plt.imshow(binary_mask, cmap="gray") aaa = plt.imshow(binary_mask, cmap="gray") plt.show() plt.imsave('output_remove_gray_area.png', aaa)
完整报错栈
Traceback (most recent call last): File "/home/joy/桌面/test_11_4/1.py", line 57, in <module> plt.imsave('output_remove_gray_area.png', aaa) File "/home/joy/miniconda3/lib/python3.9/site-packages/matplotlib/pyplot.py", line 2118, in imsave return matplotlib.image.imsave(fname, arr, **kwargs) File "/home/joy/miniconda3/lib/python3.9/site-packages/matplotlib/image.py", line 1625, in imsave pil_shape = (rgba.shape[1], rgba.shape[0]) AttributeError: 'tuple' object has no attribute 'shape'
错误原因
plt.imshow是用于在matplotlib画布上渲染图像的函数,它返回的是AxesImage对象(用于管理画布上的图像元素),并非图像的原始numpy数组。而plt.imsave要求传入的参数是图像的numpy数组,直接传入plt.imshow的返回值会导致类型不匹配,触发报错。
解决方案
直接传入生成图像的numpy数组binary_mask给plt.imsave,同时指定cmap="gray"参数,确保保存的图像和plt.imshow显示的效果一致:
修改代码最后一行:
# 替换原错误代码 plt.imsave('output_remove_gray_area.png', binary_mask, cmap="gray")
补充说明
- 如果是RGB彩色图像,无需指定
cmap参数,直接传入彩色图像数组即可; - 若需要保存画布上的完整绘图(包括标题、坐标轴等元素),可以使用
fig.savefig()方法,而非plt.imsave。
内容的提问来源于stack exchange,提问作者user20384021
相关产品推荐
相关产品推荐

