[Matplotlib puzzle] Python reads the image sequence and displays it in an image

1. Problem description

In papers or scientific research writing, it is often encountered that multiple figures are placed in one figure for easy reading.

This problem can be solved with python's matplotlib and opencv. (Or read the image with PIL) The effect is as follows:
image sample

Two, the solution

1. File structure

In response to this problem, my directory structure is as follows:

  • mask (folder mask_0.png, mask_19.png20 sequence pictures from to are stored below)
  • visualize.py (python script for execution and visualization)

2. visualize.py code

import os

import matplotlib.pyplot as plt
import cv2 as cv

fig = plt.figure()
path = './mask'	 # 设置好路径
prefix = 'mask_'  # 设置好文件名字的前缀
for i in range(0, 20):  # 设置图片的数目与范围
    plt.subplot(4, 5, i+1)  # 由于这里是20张图,可以设置4行5列的结构,
    						# 注意第三个参数不能为0,所以是i+1
    img = cv.imread(os.path.join(path, prefix+str(i)+'.png'))# 注意:前缀+序列号+图片格式的后缀
    plt.imshow(img)
    plt.xticks([])  # 取消x方向标注
    plt.yticks([])  # 取消y方向标注

if __name__ == '__main__':
    plt.show()

3. Some thinking and exploring

Why not enumerate(os.listdir())iterate through ?

Because os.listdir()the function will be out of order when traversing all the pictures in the directory.

For example, you will get a list like this:

['mask_0.png', 'mask_1.png', 'mask_10.png', 'mask_11.png', 'mask_2.png', ]

When such a list is visualized, it is clear that there is a certain logical sequence of segmented mask images, which will be arranged out of order, which will lead to an unattractive final result of the visualization, which is extremely bad for the picture matching of scientific research papers .

In order to pursue a rigorous and beautiful effect, the author did not use enumerate(os.listdir())the scheme for traversal.

Of course, all roads lead to Rome, if you insist on using this scheme, there is also os.listdir()a solution to the out-of-order problem

If you find it useful, you may wish to click a little like to support it~

Guess you like

Origin blog.csdn.net/Samurai_Bushido/article/details/129915578