Home > Software design >  (python) matplotlib.pyplot saving error to picture
(python) matplotlib.pyplot saving error to picture

Time:11-07

python matplotlib.pyplot saving error to picture

tool: with CV2 4.6.0 on Ubuntu 22.04.1 LTS

Problem:
my code can output plt.imshow(image) but cannot plt.imsavesave

AttributeError: 'tuple' object has no attribute 'shape'


  • the .py script:
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")


# image = imageio.imread(image_name)[:,:,:3]
# img = rgb2gray(image)

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)


img = Image.open('output_remove_gray_area.png')
text = pytesseract.image_to_string(img, lang='eng')

print("file name" ,"output_remove_gray_area", ".png")

print("size")

print(img.size)

print(text)
  • output:
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'

I expect to save the image which im.show is already success

CodePudding user response:

Use plt.imsave("output_remove_gray_area.png", binary_mask, cmap="gray") instead of saving aaa which is the return value of plt.imshow() and not your actual image.

  • Related