OpenCV/Maplotlib在用户输入后关闭窗口



我想使用OpenCV或Matplotlib来显示图像,要求用户输入(在终端上(并在输入后关闭图像。

以下是我在OpenCV上尝试的内容:

cv.imshow("window", image)
cv.waitKey(0)
label = int(input())
cv.destroyAllWindows()

与Matplotlib:

plt.axis("off")
plt.imshow(image)
plt.show()
label = int(input())
plt.close("all")

由于plt.show()cv.waitKey()都是"零";停止";函数冻结执行。显示图像并提示输入,但窗口未关闭。

正如您已经提到的,这两个操作都是阻塞的,因此您将无法使用真实的终端输入。尽管如此,您可以在不需要实际终端的情况下模仿这种行为。

因此,在显示图像后,您只需按下一些数字键(由于您转换为int,我认为您只想输入整数值(,将这些键连接在一些中间字符串中,使用一些最终的非数字键,例如x,停止输入,最后将字符串转换为您的最终数值。

这将是一些代码片段:

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))

我不知道你想对输入做什么,但上面的脚本可以在其他具有不同图像的循环中使用,例如

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
OpenCV:      4.4.0
----------------------------------------

最新更新