IPython Notebook 中 OpenCV 的 waitKey() 替代方案
OpenCV's waitKey() alternative in IPython Notebook
我试图在我的 Jupiter Notebook 中使用 cv2.imshow(img)
显示带有 cv2 库的图像,它按预期显示,但我无法使用或不知道如何使用 cv2.waitKey(0)
,因此单元格不会停止执行。
cv2.waitKey(0)
在脚本中有效,但在 Notebook 中无效。
这是一个片段:
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
如何在不重新启动整个内核的情况下停止执行单元?
所以,感谢@Micka,这是解决方案:
必须先写cv2.startWindowThread()
,解释here。
我发现 primoz
的答案非常有用。这是一个函数的代码,它从指定路径读取图像,绘制图像,等待任何输入关闭 window 和 returns 图像 object.
import cv2
def cv2_imshow(path, title):
"""
function:
- reads image from `path`,
- shows image in a separate window,
- waits for any key to close the window.
return: image object
"""
img = cv2.imread(path)
cv2.startWindowThread()
cv2.imshow(title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img
使用图片路径和标题调用函数:
img_raw = cv2_imshow(path = r'img\example\test.png', title = "raw image")
我试图在我的 Jupiter Notebook 中使用 cv2.imshow(img)
显示带有 cv2 库的图像,它按预期显示,但我无法使用或不知道如何使用 cv2.waitKey(0)
,因此单元格不会停止执行。
cv2.waitKey(0)
在脚本中有效,但在 Notebook 中无效。
这是一个片段:
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
如何在不重新启动整个内核的情况下停止执行单元?
所以,感谢@Micka,这是解决方案:
必须先写cv2.startWindowThread()
,解释here。
我发现 primoz
的答案非常有用。这是一个函数的代码,它从指定路径读取图像,绘制图像,等待任何输入关闭 window 和 returns 图像 object.
import cv2
def cv2_imshow(path, title):
"""
function:
- reads image from `path`,
- shows image in a separate window,
- waits for any key to close the window.
return: image object
"""
img = cv2.imread(path)
cv2.startWindowThread()
cv2.imshow(title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img
使用图片路径和标题调用函数:
img_raw = cv2_imshow(path = r'img\example\test.png', title = "raw image")