Python - How to use OpenCV imshow() in Jupyter Notebook

Lets flair it Python-OpenCV way:

Looks like you are building a deepfake model using OpenCV inside a Jupyter notebook.You installed everything, all the dependent libraries, packages. You read your image using imread() function, changed the color image to greyscale. Everything was working perfectly fine until you thought of viewing your greyscale image using imshow() function !!!!!! your jupyter notebook freezes and ask to restart the kernel and you see few error messages like below:

 

 

Now you also need to restart your Jupyter Notebook kernal, means run all the cells again.

So what is the solution, one solution is to use matplotlib to see the image, but this is what you are not here for. So let see the steps involved to view the image using OpenCV imshow() that too in Jupyter Notebook.

Steps Involved :

1) Read the image

image = cv2.imread("images/sample.png")

2) Convert to greyscale

image_greyscale = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) 

3) View greyscale image

cv2.imshow("source_image",image_greyscale)

4) To tell OpenCV not to close the window immediately, instead wait for a keypress.

cv2.waitKey(0)

5) Close the image window

cv2.destroyAllWindows()

After running few lines of code you will be able to see the greyscale image. Good Job!!!!!

 Final image :

 

Note : To close the image window, DON'T CLICK THE X BUTTON, instead press any key on your keyboard!!!! and you are all set.

So in this article, we saw how to use imshow() function in jupyter notebook without killing the kernel.

 
See you in the next article, til then Happy Learning, Happy Exploring.



 

Comments

Post a Comment