0

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")
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
imtinan
  • 191
  • 12
  • 1
    I think you may need to add the folder separator `\ ` between folder name and image name. Try `plt.savefig(di+"\\"+str(i)+".png")`? A nicer OS-independent solution would be to use os.path.join as explained [here](https://stackoverflow.com/questions/16010992/how-to-use-directory-separator-in-both-linux-and-windows-in-python) and do `img_name = str(i)+".png"` and `os.path.join(di, img_name)` – freerafiki May 29 '20 at 14:47
  • 1
    thanks! i have used first method and it works. – imtinan May 29 '20 at 15:12

2 Answers2

1

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.


seralouk
  • 30,938
  • 9
  • 118
  • 133
1

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)
Bugface
  • 313
  • 2
  • 7