【问题标题】:Using imshow methods in a for loop to print multiple images在 for 循环中使用 imshow 方法打印多个图像
【发布时间】:2020-12-25 21:29:24
【问题描述】:

我有一个简单的 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],它应该打印图像的两个部分。但是当我运行上面的单元格时,它只打印一个图像,这是图像的最后一部分。是否可以不覆盖其他图像并全部打印?

【问题讨论】:

    标签: python matplotlib google-colaboratory cv2


    【解决方案1】:

    您应该尝试在每个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])
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多