pythonimage

How to open an image, parse input from user, and close the image afterwards in Python?


This answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions:

How can one open an image in Python, then let the user answer questions about it in the CLI, and close the image afterwards?

Contstaints

  1. Don't use sub-process.
  2. Don't start killing processes that happen to match a substring.
  3. In essence, use a Python-only method that opens an image and then closes that, and only that image, with control, whilst allowing other code (that allows user interaction) to be executed in between.

Solution

  • The answer below opens an image from a file path in a separate Window, then asks the questions in the CLI. After the questions are answered by the user, the image is closed.

    Requirements

    pip install tensorflow
    pip install matplotlib
    

    Solution

    def make_receipt_label(img_filepath):
        """
        Opens an image, asks the user questions about it, and returns the answers.
    
        Args:
            img_filepath: The path to the image file.
    
        Returns:
            A dictionary containing the user's answers to the questions.
            Returns None if there is an issue opening the image.
        """
        
        from tensorflow import io
        from tensorflow import image as img
        from matplotlib import pyplot as plt
        tensor_img = io.read_file(img_filepath)
        tensor_img = img.decode_png(tensor_img, channels=3)
        plt.ion()
        plt.imshow(tensor_img)
        plt.show(block=False)
        
        root=tk.Tk()
        root.withdraw()
    
        answers = {}
        answers["image_colour"] = input("0. What is the image colour? ")
        answers["total"] = input("1. Another question? ")
        plt.close()
        plt.ioff()
        root.destroy()
    
        return answers
    
    

    Satisfied constraints

    It does not use subproces it does not try to kill processes with a pid that matches some string, it uses pure Python.