luffy
luffy

Reputation: 25

How to use subplot in this for loop to display multiple pictures in single figure?

This is my code. I want to display multiple images using Matplotlib subplot. The code is about splitting an image into 4 parts. Then I want to show the image parts, but this code shows them one after the other.

import cv2
from matplotlib import pyplot as plt

im = cv2.imread("D:\\joker.jpg")
imgheight=im.shape[0]
imgwidth=im.shape[1]

y1 = 0
M = imgheight//2
N = imgwidth//2

for y in range(0,imgheight,M):
    for x in range(0, imgwidth, N):
        y1 = y + M
        x1 = x + N
        tiles = im[y:y+M,x:x+N]

        # cv2.rectangle(im, (x, y), (x1, y1), (0, 255, 0))
        gg =cv2.cvtColor(tiles, cv2.COLOR_BGR2RGB)
        # cv2.imwrite("save" + str(x) + '_' + str(y)+".png",tiles)

        plt.imshow(gg)
        plt.xticks([]), plt.yticks([])
        plt.show()

Upvotes: 1

Views: 1272

Answers (1)

HansHirse
HansHirse

Reputation: 18925

You must actually use the subplot command before every image to be shown. Also, it might be beneficial to move the plt.show() outside the nested loop.

Here would be my solution for a modified code of yours:

k = 0                                                   # Initialize subplot counter
for y in range(0,imgheight,M):
    for x in range(0, imgwidth, N):
        k += 1
        y1 = y + M
        x1 = x + N
        tiles = im[y:y+M,x:x+N]
        gg =cv2.cvtColor(tiles, cv2.COLOR_BGR2RGB)
        plt.subplot(2, 2, k)                            # Address proper subplot in 2x2 array
        plt.imshow(gg)
        plt.xticks([]), plt.yticks([])
plt.show()                                              # Moved plt.show() outside the loop

That's the output for my standard test image:

Output

Hope that helps!

Upvotes: 1

Related Questions