使用用户输入提示在循环中一个接一个地显示图像

时间:2018-03-18 09:06:23

标签: python windows-10 pycharm

我正在编写一个代码,在用户发送输入信号之后会逐个显示图像。以下是我的代码

import  numpy as np
import  matplotlib.pyplot as plt
from logistic_regression_class.utils_naseer import getData
import time
X,Y=getData(balances=False)  // after getting X data and Y labels
# X and Y are retrieved using famous kaggle facial expression dataset
label_map=['Anger','Disgust','Fear','Happy','Sad','Surprise','Neutral']

plt.ion()
for i in range(len(Y)):
    x=X[i]
    plt.figure()
    plt.imshow(x.reshape(48,48),cmap='gray')
    plt.title(label_map[Y[i]])
    plt.show()
    _ = input("Press [enter] to continue.")
    plt.close()

输出:

我只得到没有数据的空白图像,每次按下回车我都会得到一个新的空白图像。但是当我删除了plt.close()时,所有的图都显示在单独的窗口中,但那将是太多的窗口弹出。 我还使用了stackoverflow this链接的建议。

使用命令输入一个接一个地在循环中显示图像的正确方法是什么?

屏幕截图:

a)使用plt.close()

enter image description here

b)没有plt.close()

enter image description here

2 个答案:

答案 0 :(得分:0)

我遇到了一个非常类似的问题,并且在for循环中放置plt.ion()对我有用。像这样:

for i in range(len(Y)):

    x=X[i]
    plt.ion()
    plt.figure()
    plt.imshow(x.reshape(48,48),cmap='gray')
    plt.title(label_map[Y[i]])
    plt.show()
    _ = input("Press [enter] to continue.")
    plt.close()

答案 1 :(得分:0)

我正在尝试为图像标签程序实现类似的功能(即显示图像,接受用户输入并将图像放置在正确的文件夹中)。

我遇到了一些问题,使它正常工作的唯一方法是创建一个线程(我知道它很杂乱,但可以正常工作!),该线程允许用户在图像打开时进行输入,然后在输入图像后将其关闭。我将plt对象传递给线程,因此可以从那里关闭它。我的解决方案看起来像这样...也许您可以使用类似的方法!

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import threading
from shutil import copyfile
import msvcrt

#define folders 
CAR_DATA = 'car_data'
PASSENGER = 'passenger'
NO_PASSENGER = 'no_passenger'
UNSURE = 'unsure'
extensionsToCheck = ['jpg', '.png']

listing = os.listdir(CAR_DATA)

def userInput(plt, file_name):
    print('1:No Passenger - 2:Passenger - Any Other:Unsure - e:exit')
    user_input = msvcrt.getch()
    user_input = bytes.decode(user_input)
    if(user_input=='1'):
        print("No Passenger")
        copyfile(CAR_DATA+'/'+file_name, NO_PASSENGER+'/'+file_name)
    elif(user_input=='2'):
        print("Passenger")
        copyfile(CAR_DATA+'/'+file_name, PASSENGER+'/'+file_name)
    elif(user_input=="e"):
        print("exit")
        os._exit(0)
    else:
        print("unsure")
        copyfile(CAR_DATA+'/'+file_name, UNSURE+'/'+file_name)
    plt.close()

def main():
    for file in listing:
        if any(ext in file for ext in extensionsToCheck):
            plt.figure(file)
            img=mpimg.imread(CAR_DATA + '/' + file)
            imgplot = plt.imshow(img)
            plt.title(file)
            mng = plt.get_current_fig_manager()
            mng.full_screen_toggle()
            threading.Thread(target=userInput, args=(plt,file)).start()
            plt.show()

if __name__ == '__main__':main()