在 for 循环中使用 imshow 方法打印多张图像

Using imshow methods in a for loop to print multiple images

我有一个简单的 2d numpy 数组,它是灰度图像的像素图。我正在尝试打印图像的某些部分。我的密码是

from google.colab import drive
drive.mount('/content/drive')
import numpy as np
import matplotlib.pyplot as plt
import cv2

img = cv2.imread('/content/drive/My Drive/Colab Notebooks/sample2.jpg') # the source file is correctly mounted
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

i = 0
while i < (len(roi) - 1): # roi is a list of strictly increasing positive integers 
  print(roi[i], roi[i+1])
  plt.imshow(img_gray[roi[i]:roi[i+1]], cmap='gray')
  i += 1

例如,如果roi = [10, 40, 50, 100],它应该打印图像的两个部分。但是当我 运行 上面的单元格时,它只打印一张图像,这是图像的最后一部分。是否可以不覆盖其他图像并全部打印?

您应该尝试在每个 plt.imshow(...):

之后调用 plt.show()
i = 0
while i < (len(roi) - 1): # roi is a list of strictly increasing positive integers 
  print(roi[i], roi[i+1])
  plt.imshow(img_gray[roi[i]:roi[i+1]], cmap='gray')
  plt.show() # <----- this will show all plots
  i += 1

或者,如果你想保留一个更好、更有条理的情节,你可以使用子图,尽管你应该说明你想要多少个子图,这里是一个随机输入的例子:

import matplotlib.pyplot as plt
import numpy as np

ims = np.random.randn(3, 224, 224)

fig, ax = plt.subplots(1, 3)
for i in range(3):
    ax[i].imshow(ims[i])

最后一个示例将绘制水平排列的图像: