matplotlib Colab环境在调用www.example.com()后不显示输入plt.show

juud5qan  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(138)

我目前正在写一个colab notebook,我需要迭代地打开一个图像,使用input()函数对其给予投票,然后清除输出并处理下一个图像。代码如下所示:

import os
import cv2
import matplotlib.pyplot as plt
import numpy as np

imgs_list = ['img1.jpg', 'img2.jpg']

for i in imgs_list:
  img_path = os.path.join(os.getcwd(), i)
  img = cv2.imread(img_path)
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 

  height, width, _ = img.shape

  if height >= width:
    plt.figure(figsize=(12,10))
  else:
    plt.figure(figsize=(10,12))

  plt.imshow(img)
  plt.axis('off')
  plt.show()

  vote = 0
  while vote < 1 or vote > 10:
      try:
          vote = int(input("Give a vote from 1 to 10: "))
      except ValueError:
          vote = 0
      if vote not in range(1,11):
          print('Insert valid value')

我在Jupyter Notebook上尝试了这段代码,它工作正常,当我切换到colab时(我不得不这样做,因为我需要发送笔记本),我尝试运行以下单元格,在plt.show()之后,我看不到任何输入栏,我可以在其中键入数字。
有没有办法解决这个问题?

uujelgoq

uujelgoq1#

this answer中所述,您可以在IPython中使用display模块。我认为以下方法应该可以工作,但你必须测试它:

import os
import cv2
import matplotlib.pyplot as plt
import numpy as np

# import display
from IPython import display

imgs_list = ['img1.jpg', 'img2.jpg']

for i in imgs_list:
  img_path = os.path.join(os.getcwd(), i)
  img = cv2.imread(img_path)
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 

  height, width, _ = img.shape

  # clear any existing figure
  plt.clf()

  if height >= width:
    plt.figure(figsize=(12,10))
  else:
    plt.figure(figsize=(10,12))

  plt.imshow(img)
  plt.axis('off')
  
  # display the figure
  display.display(plt.gcf())
  display.clear_output(wait=True)

  vote = 0
  while vote < 1 or vote > 10:
      try:
          vote = int(input("Give a vote from 1 to 10: "))
      except ValueError:
          vote = 0
      if vote not in range(1,11):
          print('Insert valid value')

相关问题