Python opencv.imshow 会导致 jupyter notebook 崩溃

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46236180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:32:28  来源:igfitidea点击:

opencv.imshow will cause jupyter notebook crash

pythonopencvubuntujupyter-notebook

提问by scott huang

I check other question on google or stackoverflow, they are talking about run cv2.imshow in script, but my code run in jupyter notebook.

我在 google 或 stackoverflow 上查看其他问题,他们正在谈论在脚本中运行 cv2.imshow,但我的代码在 jupyter notebook 中运行。

Here is my configuration:

这是我的配置:

  1. ubuntu 16.4x64

  2. python 3.5

  3. opencv 3.1.0

  1. Ubuntu 16.4x64

  2. 蟒蛇 3.5

  3. opencv 3.1.0

I start a jupyter notebook: here is the code I put it notebook:

我启动了一个 jupyter notebook:这是我放在 notebook 中的代码:

%pylab notebook
import cv2

cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey() #image will not show until this is called
cv2.destroyWindow('HelloWorld') #make sure window closes cleanly

When I execute these code. image will show in a pop up window, but I can not close this window by clicking the x on the top right corner, and a moment later, system will prompt me that the window is not responding, it will give me 2 choices: "wait" , "fore quit". if I hit wait, then It will show the same prompt later, If I hit 'fore quit', then the jupyter notebook kernel die and I have to start over.

当我执行这些代码时。图像将显示在弹出窗口中,但我无法通过单击右上角的 x 关闭此窗口,稍后,系统会提示我该窗口没有响应,它会给我 2 个选择:“等待”,“退出”。如果我点击等待,那么稍后它会显示相同的提示,如果我点击“退出前”,那么 jupyter notebook 内核就会死掉,我必须重新开始。

I google around, many solution suggest that I should add this code

我谷歌搜索,许多解决方案建议我应该添加此代码

cv2.startWindowThread()

before imshow, but situation get worse, the kernel hang forever!. anybody have some idea what's going on.

之前imshow,但情况变得更糟,内核永远挂起!。任何人都知道发生了什么。

Here is the pic of my error: enter image description here

这是我的错误图片: 在此处输入图片说明

回答by Ritu dhoot

%matplotlib inline
#The line above is necesary to show Matplotlib's plots inside a Jupyter Notebook

import cv2
from matplotlib import pyplot as plt

#Import image
image = cv2.imread("input_path")

#Show the image with matplotlib
plt.imshow(image)
plt.show()

回答by mannyglover

I was having a similar problem, and could not come to a good solution with cv2.imshow()in the Jupyter Notebook. I followed this stackoverflow answer, just using matplotlib to display the image.

我遇到了类似的问题,无法cv2.imshow()在 Jupyter Notebook 中找到一个好的解决方案。我按照这个 stackoverflow answer,只是使用 matplotlib 来显示图像。

import matplotlib.pyplot as plt
# load image using cv2....and do processing.
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# as opencv loads in BGR format by default, we want to show it in RGB.
plt.show()

回答by Saibot

The API documentation for cv2.waitKey()notes the following:

cv2.waitKey()API 文档指出以下内容:

This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing.

此函数是 HighGUI 中唯一可以获取和处理事件的方法,因此需要定期调用它以进行正常的事件处理,除非在负责事件处理的环境中使用 HighGUI。

So perhaps calling the function in an endless loop would make the window responsive? I haven't tested this, but maybe you would like to try the following:

那么也许在无限循环中调用该函数会使窗口响应?我还没有测试过这个,但也许你想尝试以下方法:

import cv2

cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('img', cvim2disp)
while(True):
    k = cv2.waitKey(33)
    if k == -1:  # if no key was pressed, -1 is returned
        continue
    else:
        break
cv2.destroyWindow('img')

回答by Vivek Kumar

This will help you understand what is happening:

这将帮助您了解正在发生的事情:

import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey(0) 
cv2.destroyWindow('HelloWorld')

waitKey(0)method is waiting for an input infinitely. When you see a frame of the corresponding image, do not try to close the image using close in top right corner.

waitKey(0)方法无限等待输入。当您看到相应图像的一帧时,请勿尝试使用右上角的关闭来关闭图像。

Instead press some key. waitkeymethod will take that as an input and it will return back a value. Further you can also check which key was pressed to close the frame.

而是按某个键。waitkey方法将把它作为输入,它会返回一个值。此外,您还可以检查按下哪个键来关闭框架。

Additionally waitKey(33)will keep the frame active for 33 ms and then close it automatically.

此外,waitKey(33)还将使帧保持活动状态 33 毫秒,然后自动关闭。

destroyWindow()will destroy the current frame if there. destroyAllWindows()will destroy all the frames currently present.

destroyWindow()如果存在,将破坏当前帧。 destroyAllWindows()将销毁当前存在的所有帧。

This will solve.

这将解决。

回答by Abhinav Bangia

The new window that opens up from Jupyter uses the same kernel as notebook. Just add this below to the code and it would work fine.

从 Jupyter 打开的新窗口使用与 notebook 相同的内核。只需将其添加到代码中,它就可以正常工作。

cv2.waitKey(0)
cv2.destroyAllWindows()

回答by Mazhar Hossain

image = cv2.imread(file_path)
while True:
    # Press 'q' for exit
    exit_key = ord('q')
    if cv2.waitKey(exit_key) & 255 == exit_key:
        cv2.destroyAllWindows()
        break
    cv2.imshow('Image_title', image)

回答by Kardi Teknomo

The following code works fine in Jupyter to show one image

以下代码在 Jupyter 中工作正常以显示一张图像

%matplotlib inline
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(videoFName)
ret, image = cap.read()
image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
plt.imshow(image)
plt.show()

If you want to show the video instead of an image in a separate window, use the following code:

如果要在单独的窗口中显示视频而不是图像,请使用以下代码:

import cv2
cap = cv2.VideoCapture(videoFName)
while cap.isOpened():
    ret, image = cap.read()
    image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
    cv2.imshow('image',image)

    k = cv2.waitKey(30) & 0xff # press ESC to exit
    if k == 27 or cv2.getWindowProperty('image', 0)<0:
        break
cv2.destroyAllWindows()
cap.release()

Make sure the window name match, otherwise it will not work. In this case I use 'image' as window name.

确保窗口名称匹配,否则将无法工作。在这种情况下,我使用“图像”作为窗口名称。

回答by Fred Guth

I am not sure if you can open a window from Jupyter Notebook. cv2.imshow expects a waitKey which doesn't work in Jupyter.

我不确定您是否可以从 Jupyter Notebook 打开一个窗口。cv2.imshow 需要一个在 Jupyter 中不起作用的 waitKey。

Here is what I have done (using OpenCV 3.3):

这是我所做的(使用 OpenCV 3.3):

from IPython.display import display, HTML
import cv2
import base64

def imshow(name, imageArray):
     _, png = cv2.imencode('.png', imageArray)
     encoded = base64.b64encode(png)
     return HTML(data='''<img alt="{0}" src="data:image/png;base64, {1}"/>'''.format(name, encoded.decode('ascii')))

img = cv2.imread('./media/baboon.jpg',cv2.IMREAD_COLOR)
imshow('baboon', img)

If you don't need to use cv2, just:

如果您不需要使用 cv2,只需:

from IPython.display import Image
Image('./media/baboon.jpg')