27

I am running OpenCV through Jupyter Notebooks and whenever I try to run cv2.imshow() the kernel crashes, no error message or helpful hint - just a plain

The Kernel appears to have died. It will restart automatically.

Here is the code I am running...

import cv2 
input = cv2.imread('images/input.jpg')
cv2.imshow('Hello World', input)
cv2.waitKey(0)
cv2.destroyAllWindows()

The code works (albeit differently) when I run the below...

%matplotlib inline
from matplotlib import pyplot as plt
import cv2
image = cv2.imread('images/input.jpg')
plt.imshow(image)
plt.show()

FYI I am using a completely unaltered copy of BitFusion on AWS.

https://aws.amazon.com/marketplace/pp/B01EYKBEQ0?ref=cns_srchrow

Any idea what could be going wrong?

Mike de H
  • 599
  • 2
  • 6
  • 13
  • 1
    P.S. I am accessing the JN through Chrome running on Windows 7. – Mike de H May 12 '17 at 18:31
  • 4
    Matplotlib can render into images, which can then be displayed as part of the HTML notebook. The OpenCV convenience GUI utilities are purely client side -- `imshow` shows the image in a GUI window, `waitKey` pumps the message loop, etc. It doesn't make any sense running them on the server side. – Dan Mašek May 12 '17 at 20:34
  • I was experiencing the same problem. The following answer helped me. https://stackoverflow.com/questions/19285562/python-opencv-imread-displaying-image Make sure there aren't any syntax errors if it still crashes. – hamza7292 Feb 09 '19 at 07:40

4 Answers4

8

I can't explain the behavior of your code right now but you can use the below code to achieve the above behavior.

%matplotlib inline
from matplotlib import pyplot as plt
import cv2
image = cv2.imread('images/input.jpg')
plt.imshow(image)
plt.show()
Puneet Jindal
  • 147
  • 2
  • 10
  • 8
    That's not what the question asks. cv2. imshow() doesn't work. Using plt doesn't help the question. – Dimitri Dec 06 '19 at 19:27
  • Additionally, the matplotlib display will invert the colour channels and display a BGR image as RGB. – S3DEV Nov 24 '22 at 20:17
5

To view images with cv2.imshow on AWS, you need to enable X11 forwarding so the graphics can be run on the server and displayed locally. This can be done by ssh-ing with the -Y option:

ssh -Y username@hostname

If the images are larger, you will also need to compress the data using -C:

ssh -Y -C username@hostname

The terminal used to ssh into AWS will need to be left open as long as you're displaying images from the notebook.

A Kruger
  • 2,289
  • 12
  • 17
0

So for me, the issue was fixed by placing a while loop that ends when you press the key D on your keyboard

import cv2 as cv
img = cv2.imread('Images/1.jpg')
while True: 
    cv.imshow('ImageDisplay',img)
    if cv.waitKey(20) & 0xFF == ord('d'):
        break
cv.destroyAllWindows()
0

update numpy !!

pip install -U numpy --user
Manav Patadia
  • 848
  • 7
  • 12