imtinan
imtinan

Reputation: 181

Matplotlib figure is not saving in a specific folder

I am trying to save matplotlib figure in r"C:\Users\USER\Handcrafted dataset\binary_image". but instead of saving figure in binary_image folder figure is saving in Handcrafted dataset folder. And the image name is becoming binary_image0.png. But i want to save figure in my desired directory as i.png .How can i fix this?

di=r"C:\Users\USER\Handcrafted dataset\binary_image"
for i,img in enumerate(images):
    img = rgb2gray(img)
    plt.figure(figsize=(5,5))
    plt.imshow(img ,cmap='gray')
    plt.savefig(di+str(i)+".png")

Upvotes: 0

Views: 1883

Answers (2)

Bugface
Bugface

Reputation: 313

Using os.path.join or pathlib.Path is better.

import os

fn = "file_{}.png".format(i)
fn = os.path.join(dir, fn)
plt.savefig(fn)

or

from pathlib import Path

dir = Path(dir)
fn = dir / "file_{}.png".format(i)
plt.savefig(fn)

Upvotes: 1

seralouk
seralouk

Reputation: 33147

You forgot a backslash:

plt.savefig(save_to + '\' + str(i) + '.png')

Note: dir is a build-in function -- do not name your variable like that.


Upvotes: 1

Related Questions