Displaying an Image with OpenCV inside Jupyter Lab
Date: 2021-04-25 22:30:23, by Pc Ng
Table of Content
Displaying an Image with OpenCV inside Jupyter Lab⚓︎
cv2.imshow
is often used to display image. However, calling cv2.imshow
in Jupyter Lab will fire up a new window.
Displaying an Image with cv2.imshow
⚓︎
I took some photos when I visited Melaka (a small state in Malaysia) by myself in year 2020 (When coronavirus hasn't hit Malaysia yet).
I can use the cv2.imread
and cv2.imshow
to read the image.
import cv2
melaka_img = cv2.imread('melaka.jpg')
cv2.imshow('Window', melaka_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
A large window popped up and show the image of Melaka. However, the size of the image is too big to fit in my single computer display, and there is no way to adjust the size of the window. Even though I connected my computer to another two external displays, some parts of the image are still not visible.
Displaying an Image within the Jupyter Lab⚓︎
There are a few methods to display an image read by openCV inside Jupyter Lab. The common way is to use the imshow
in Matplotlib.
In this post, we are going to look at another way to display the image inside the Jupyter Lab.
Since Jupyter Lab is working within a web browser, we can use the HTML method to display the image inside the Jupyter Lab.
Let's import the related dependencies.
from IPython.display import display, HTML
import base64
import cv2
Next, let's define a function that takes in the image name, the image data nad the display size as the input arguments and return an HTML content.
def imshow(name, img, size):
_, img = cv2.imencode('.jpg', img)
encoded = base64.b64encode(img)
return HTML(data='''<img alt="{0}" src="data:image/img;base64, {1}" style="width:{2}px"/>'''.format(name, encoded.decode('ascii'), size))
Now we can call the imshow
function that we have defined to display the image inside Jupyter Lab.
melaka_img = cv2.imread('melaka.jpg')
imshow('Melaka', melaka_img, 200)
Let's change the size and see the output.
imshow('Melaka', melaka_img, 500)
Note⚓︎
The imshow
function can be further customized by including some style properties to define the image's style.