user2126062
user2126062

Reputation: 111

plotting images in a for loop

I see there are similar questions but I'm still struggling to get this right.

I am iterating through a folder and getting images into a format to be printed out:

'''

output_files = np.random.choice(data_files,  size=20, replace=False)

for img_name in output_files:
    some code that gets the images right for printing 
    img = cv2.imread(os.path.join(data_dir,img_name))
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    plt.imshow(img)
    plt.show()

''' The above works well enough to plot the 20 images one under each other.

I want to use the subplot function to plot these images in a 5 by 4 layout. Ive tried various things but I'm struggling because I either print out 20 of each image or only the last image 20 times so I'm obviously doing something wrong with my loops.

Ive added this to the code but thats now printing 20 of each image underneath each other.

'''

output_files = np.random.choice(data_files,  size=20, replace=False)

w = 10
h = 10
fig = plt.figure(figsize=(8, 8))
columns = 4
rows = 5


for img_name in output_files:
  img_age, img_gender = img_name.split('_')[:2]
  img_age = int(img_age)
  img_gender = 'Male' if img_gender=='0' else 'Female'
  img = cv2.imread(os.path.join(data_dir,img_name))
  img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

  for i in range(1, columns*rows +1):
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
    plt.show()

'''

Upvotes: 0

Views: 2377

Answers (1)

Eumel
Eumel

Reputation: 1433

Yes its your loops.

For each image you load you create a 5x4 subplot and fill that in. Instead create your plot once at the top and fill in your images later

fig, axes = plt.subplot(5,4)
for i, img_name in enumerate(output_files):
    img = #your image loading here
    axes[i//4,i%4] = plt.imshow(img) 
plt.show()

Upvotes: 1

Related Questions