0

I want to save 4 images in 4 directories and name of directories are 4,5,6,7 (for instance image 1 in directory 4 and image 2 in directory 5 and so on) but it seems my for loop it's not correct and just saves the last image in directory 4.

import numpy as np
import matplotlib.pyplot as plt
import os

pixels = 600
my_dpi = 100
num_geo=3

coord = np.array([[[-150, -200], [300, -200], [300, 0], [150, 200], [-150, 200]],
                  [[-300, -200], [200, -300], [200, -50], [200, 300], [-150, 200]],
                  [[-140, -230], [350, -260], [350, 0], [140, 200], [-180, 220]],
                  [[-180, -240], [370, -270], [370, 0], [170, 200], [-190, 230]]])

for i in range(4):
    geo = coord[i, :, :]
    print(coord[i])
    fig = plt.figure(num_geo,figsize=( pixels/my_dpi,  pixels/my_dpi),facecolor='k', dpi=my_dpi)  
    plt.axes([0,0,1,1])
    rectangle = plt.Rectangle((-300, -300), 600, 600, fc='k')
    plt.gca().add_patch(rectangle)
    polygon = plt.Polygon(coord[i],color='w')
    plt.gca().add_patch(polygon)
    plt.axis('off')
    plt.axis([-300,300,-300,300])
for j in range(4,8):  
    os.mkdir("fig/%d" % j)
    plt.savefig('fig/%d/%d.jpg' % (j,i), dpi=my_dpi)
    plt.close()
1
  • you don't need for j in range(4,8):. Use savefig in loop for i in range(4): and use j = i+4 in file name Commented Feb 24, 2020 at 18:48

1 Answer 1

1

You don't need second loop - besides it runs after first loop when i has value 4 so you get all images in directory 4

You need j = i + 4

for i in range(4):
    geo = coord[i, :, :]
    print(coord[i])
    fig = plt.figure(num_geo,figsize=( pixels/my_dpi,  pixels/my_dpi),facecolor='k', dpi=my_dpi)  
    plt.axes([0,0,1,1])
    rectangle = plt.Rectangle((-300, -300), 600, 600, fc='k')
    plt.gca().add_patch(rectangle)
    polygon = plt.Polygon(coord[i],color='w')
    plt.gca().add_patch(polygon)
    plt.axis('off')
    plt.axis([-300,300,-300,300])
    j = i + 4
    os.mkdir("fig/%d" % j)
    plt.savefig('fig/%d/%d.jpg' % (j,i), dpi=my_dpi)
    plt.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.