Simon Kiely
Simon Kiely

Reputation: 6040

Save contour as image

I am trying to convert a folder to show the contours of each image. The code will show the image when I plot it, but not save it to image. How can I save it to an image ?

Current error message :

ValueError: 'arr' does not have a suitable array shape for any mode.


import matplotlib.pyplot as plt
import os
from PIL import Image

i=0
directory_in_str='C:\\directory'
directory_output='C:\\output_directory'
for file in os.listdir(directory_in_str):
        print(file)

        # read image to array
        im = array(Image.open(join(directory_in_str,file)).convert('L'))

        # show contours with origin upper left corner
        im = plt.contour(im, levels=[100], colors='black', origin='image')

        scipy.misc.imsave(directory_output +'image' + str(i) + '.jpg', im)
        i+=1

print('done')

Thanks !

Upvotes: 0

Views: 3978

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339120

The imsave function is meant to be used with numpy arrays.

As an example:

import matplotlib.pyplot as plt
import numpy as np

arr = np.random.rand(10,10)
plt.imsave("test.png", arr)

Here you want to save the matplotlib figure instead. As stated in @lelouchkato's answer, this would be done using the plt.savefig function.

Mind that you need to save to an existing directory, so you probably want an additional backspace \\ in your path

plt.savefig(directory_output +'\\image' + str(i) + '.jpg')

Upvotes: 1

lelouchkako
lelouchkako

Reputation: 123

try the following plt.savefig function.

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html

Upvotes: 0

Related Questions