Processing and Showing Images in Jupyter Notebook

This jupyter notebook shows how to process and showing images.

First, load all the necessary modules for image processing.

import numpy as np
import os
import six.moves.urllib as urllib
from PIL import Image
import cv2
import matplotlib.pyplot as plt

%matplotlib inline

Here, we define the directories from where the images are loaded.

ROOT_DIR = '/Users/sparrow/Learning/machine-learning/the-eye'
IMAGES_DIR = os.path.join(ROOT_DIR, 'object-detection', 'images')

Lets have a look at the images we are going to work on.

images = [image for image in os.listdir(IMAGES_DIR) if '.jpg' in image]
images
['16496408_16496408.jpg',
 '17251231_17251231.jpg',
 '21513152_21513152.jpg',
 '50033855_50033855.jpg',
 '50173781_50173781.jpg',
 '51513971_51513971.jpg',
 '51657478_51657478.jpg',
 '51910986_51910986.jpg',
 '52324556_52324556.jpg',
 '53226802_53226802.jpg',
 'cat_1.jpg',
 'human_2.jpg']

Show images using matplotlib

image_path = os.path.join(IMAGES_DIR, images[0])
image = plt.imread(image_path) # open as np array
print(image.shape) # width, height, channel
print(type(image))
plt.imshow(image)
plt.show()
(500, 500, 3)
<class 'numpy.ndarray'>

png

Similar can be done using OpenCV

image = cv2.imread(os.path.join(IMAGES_DIR, '51657478_51657478.jpg')) # opens as np array
print(image.shape) # width, height, channel
print(type(image))
plt.imshow(image)
plt.show()
(500, 500, 3)
<class 'numpy.ndarray'>

png

Resize image using OpenCV

image = cv2.imread(os.path.join(IMAGES_DIR, '53226802_53226802.jpg'))
image = cv2.resize(image, (250, 250), interpolation=cv2.INTER_AREA)
plt.imshow(image)
plt.show()

png

Fix distorted color of images in Jupyter Notebook

image = cv2.imread(os.path.join(IMAGES_DIR, '17251231_17251231.jpg'))

# Use this line to show the image in jupyter notebook, not for exporting images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()

png

Convert to grayscale

image = cv2.imread(os.path.join(IMAGES_DIR, '21513152_21513152.jpg'))
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(image, cmap=plt.get_cmap('Greys_r'))
plt.show()

png

Draw rectangle on image

# Image bounding box
x_min, y_min = 50, 50 # Top-Left corner
x_max, y_max = 450, 450 # Bottom-Right corner

# Rectangle line color
color = (255, 0, 0) # Red

image = cv2.imread(os.path.join(IMAGES_DIR, '50033855_50033855.jpg'))
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), color, 3)
plt.title('A nice shirt')
plt.imshow(image)
plt.show()

png

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top