0

I would like to use OpenCV or Matplotlib for showing an image, asking the user for an input (on terminal) and close the image after the input.

Here's what I've tried with OpenCV:

cv.imshow("window", image)
cv.waitKey(0)

label = int(input())

cv.destroyAllWindows()

And with Matplotlib:

plt.axis("off")
plt.imshow(image)
plt.show()

label = int(input())

plt.close("all")

None have worked, since both plt.show() and cv.waitKey() are "stoping" functions they freeze the execution. The image is shown and the input is prompted, but the window isn't close.

JeanCHilger
  • 346
  • 1
  • 3
  • 12
  • 1
    In matplotlib, you can show windows in a [non-blocking behavior](https://stackoverflow.com/q/28269157/8881141). What works depends a bit on the matplotlib version, the backend, and the OS. – Mr. T Nov 25 '20 at 09:59
  • @Mr.T I've tried that but didn't work :(. – JeanCHilger Nov 25 '20 at 11:58
  • As I said, it depends on these versions. For some time, I could not convince matplotlib to update windows. Now, the [`plt.ion()`](https://matplotlib.org/3.1.1/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py) methods works - probably just an update of one of those libraries. It is also worth checking (and maybe changing) your backend - if it is not interactive, there is nothing matplotlib can do. – Mr. T Nov 25 '20 at 12:02

1 Answers1

3

As you already mentioned, both operations are blocking, so you won't to be able to use real terminal input. Nevertheless, you can mimic such a behaviour without needing an actual terminal.

So, after showing the image, you would just press some numeric keys (since you convert to int, I assume you only want to input integer values), concatenate these in some intermediate string, use some final non-numeric key, for example x, to stop the input, and finally convert the string to your final numeric value.

That'd be some code snippet:

import cv2

# Read image
image = cv2.imread('path/to/your/image.png')

# Show image
cv2.imshow('window', image)

# Initialize label string
label_as_str = ''

# Record key presses in loop, exit when 'x' is pressed
while True:

    # Record key press
    key = cv2.waitKey(0) & 0xFF

    # If 'x' key is pressed, break from loop
    if key == ord('x'):
        break

    # Append pressed key to label string
    label_as_str += chr(key)

# Convert label string to label
label = int(label_as_str)

# Close all windows
cv2.destroyAllWindows()

# Output
print(label, type(label))

I don't know what you want to do with the input, but the above script can be used inside other loops with different images for example, etc.

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
OpenCV:      4.4.0
----------------------------------------
HansHirse
  • 18,010
  • 10
  • 38
  • 67