在Jupyter-Notebook中使用循环的图像网格。怎么样?

时间:2019-05-04 10:32:44

标签: python image matplotlib grid jupyter-notebook

我想在Jupyter Notebook中以2x3矩阵格式显示图像var_1.png,...,var_40.pngenter image description here 但是,我只能手动进行:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

%matplotlib inline

img1=mpimg.imread('Variable_8.png')
img2=mpimg.imread('Variable_17.png')
img3=mpimg.imread('Variable_18.png')
          ...

fig, ((ax1, ax2, ax3), (ax4,ax5,ax6)) = plt.subplots(2, 3, sharex=True, sharey=True) 

ax1.imshow(img1)
ax1.axis('off')
ax2.imshow(img2)
ax2.axis('off')
   ....

我想要更清洁的东西。类似于列表理解的内容,它指定

image=[img(i)=mpimg.imread('Variable_(i).png') for i in [8,17,28, ..]

[ax[j].imshow(img(j)),ax[j].axis('off') for j in range(len(image))]

有帮助吗?

2 个答案:

答案 0 :(得分:1)

那又怎么样:

imgs_names = ...
imgs = [mpimg.imread(name) for name in imgs_names]

n_rows = 2
n_cols = 3
fig, axes = subplots(n_rows, n_cols)

[(axes[i][j].imshow(imgs[i*n_cols + j]), axes[i][j].axis('off')) for i in range(n_rows) for j in range(n_cols)]

Rmk:如果n_cols=1n_rows=1不起作用,因为axes是列表,而不是数组。

答案 1 :(得分:1)

如果列表理解要做的事情不止一件事,它们很快就会变得难以理解。如果列表的内容根本没有实际使用,则使用列表推导似乎也被认为是不好的风格。

因此,我提出以下建议

const {app, BrowserWindow, Menu} = require('electron');
let mainWindow;

app.on('ready', () => {
  Menu.setApplicationMenu(
    Menu.buildFromTemplate([
      {role: 'appMenu', submenu: [

        {label: 'relaunch(); exit()', click() {
          app.relaunch();
          app.exit();
        }},

        {label: 'relaunch(); quit()', click() {
          app.relaunch();
          app.quit();
        }},

        {type: 'separator'},

        {label: 'exit(); relaunch()', click() {
          app.exit();
          app.relaunch();
        }},

        {label: 'quit(); relaunch()', click() {
          app.quit();
          app.relaunch();
        }}
      ]}
    ])
  );
  mainWindow = new BrowserWindow({width: 640, height: 480});
  mainWindow.loadFile('index.html');
});