import matplotlib.pyplot as plt
import cv2
import os
root = "./data" #The folder that contains the images. Please change accordingly
lsdir = os.listdir(root)
imgs = []
for l in lsdir:
target = os.path.join(root,l)
img = cv2.imread(target)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Color conversion for display in pyplot
imgs.append(img)
shownumber = 10 #Number of images to arrange
showaxis = 1
while(showaxis*showaxis < shownumber):
showaxis += 1
cnt = 0
while(1):
#limit = 30
#if cnt >= limit:
# break
fig,axs = plt.subplots(showaxis,showaxis)
ar = axs.ravel()
for i in range(showaxis*showaxis):
ar[i].axis('off')
if i < shownumber:
ar[i].imshow(imgs[cnt])
cnt += 1
plt.show()
shownumber = 9

shownumber = 10

――I feel like I'm wondering about matplotlib every time I display an image, so I wanted to set a standard for myself.
--Since specifying row and column is subtly annoying, I wanted the code to work just by specifying the number of displays.
――I wanted to create a page where such source code would hit immediately
--Specify a folder and read it with cv2.imread, and make it an array called ʻimgs. --OpenCV is read in BGR format, so convert it to RGB format with cv2.cvtColor --If you specify the display numbershow number, find the minimum square that satisfies it, and set one side as show axis`.
while(showaxis*showaxis < shownumber):
showaxis += 1
--Prepare a graph with plt.subplots with as many rows and columns as show axis.
――Since it is troublesome to specify the vertical position and horizontal position of ʻaxs, make a series of arrays with ʻaxs.ravel ().
--Display images with ʻimshow and ʻaxis ('off') as many as show number per loop
--Keep spinning the loop until ʻimgs` runs out
Note that due to the structure of the code, an out-of-range reference error will definitely occur in the end. I wrote the escape process in the comments.
Recommended Posts