LAB 6 and 7: Image Processing Using Scikit-Image Library

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH

DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH

Name: _____________________________ Roll No: __________________________________

Signature of Lab Tutor: ____________________ Date: ________________________________

LAB 6 and 7: Image Processing using Scikit-Image Library

OBJECTIVES

Introduction to Scikit-Image Library

Introduction

Scikit-Image is a collection of algorithms for image processing. It is an open source Python


package designed for image preprocessing. Scikit-Image works with NumPy arrays. It is a
Simple and efficient tools for image processing and computer vision techniques. 

Read, Show, Save an image, data types and colorspaces

Reading an image from files/Computer: skimage.io.imread()

Example:
# importing io from skimage
from skimage import io
img = io.imread('E:\\histogram.png')

# way to show the input image


io.imshow(img)
io.show()

Reading from the skimage.data_dir

Example:
import os
import skimage
from skimage import io

filename = os.path.join(skimage.data_dir, 'camera.png')


camera = io.imread(filename)

io.imshow(camera)
io.show()

1
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
Saving an image in the computer:
Example:

import os
import skimage
from skimage import io

filename = os.path.join(skimage.data_dir, 'camera.png')


camera = io.imread(filename)

#save an image
io.imsave('E:\\test image.png',camera)

Data Types and Shape

Image ndarrays can be represented either by integers (signed or unsigned) or floats.

Example:

print(‘Shape’, camera.shape)
print(‘data type’, camera.dtype)
print(‘type’, type(camera))

Colorspaces

A color image is a 3D array, where the last dimension has size 3 and represents the red, green,
and blue channels. Color images are of shape (N, M, 3).

Example:

from skimage import io


img = io.imread('E:\\histogram.png')
print("Shape:", img.shape)
print("Values min/max:", img.min(), img.max())
io.imshow(img)
io.show()

These are just NumPy arrays. E.g., we can make a red square by using standard array slicing and
manipulation:

Example:

from skimage import io


img = io.imread('E:\\histogram.png')
print("Shape:", img.shape)
print("Values min/max:", img.min(), img.max())
img[20:120, 100:200, :] = [255, 0, 255] # [red, green, blue]
io.imshow(img)
io.show()
2
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH

Changing Image Format


The rgb2gray function is used to read an image in RGB format and convert it into the grayscale
format.

Example:

from skimage.color import rgb2gray


from skimage import io
img = io.imread('E:\\histogram.png')
img_new = rgb2gray(img)
io.imshow(img_new)
io.show()

Other two popular formats are HSV (hue, saturation, value) and HSL (hue, saturation, lightness)
which are alternative representations of the RGB format.
 Hue is a degree on the color wheel where 0 is for red, 120 is green, 240 is blue and again
360 would be red.
 Saturation represents the percentage of that color, where 0 is white and 100 is the full
color.
 Value denotes the mixture of the colors with varying amounts of black or white paint.
 Lightness is another way to show the shade of the image where 0 is black and 1 is white.

The rgb2hsv is used to convert into HSV format respectively.

Example: Changing image format form RGB to HSV

from skimage.color import rgb2hsv


from skimage import io
img = io.imread('E:\\histogram.png')
img_new = rgb2hsv(img)
io.imshow(img_new)
io.show()

Resizing an Image

resize function from skimage is used to change the size (dimensions) of an image. The input to
this function will be an image which we want to change the dimensions for the new image.

3
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
Example:
from skimage.transform import resize
from skimage import io
img = io.imread('E:\\histogram.png')
#resize image
img_resized = resize(img, (300, 300))
io.imshow(img_resized)
io.show()

Rescaling (Upscale/Downscale) Images

Rescaling images is another common computer vision technique. This implies scaling the images
by a particular factor. For example, reducing the size of each image by half (downscale) or
increasing the size of images by a factor of 2 (upscale). If the original size of all the images is the
same, say (300, 300), we can directly use the resize function and specify the required dimensions
(150, 150). But if the size of the images is different, the resize function cannot be used. We use
the rescale function and specify the scaling factor. All the images will be scaled by this factor,
based on the original size of the image.

Example:
from skimage.transform import rescale
from skimage import io
from matplotlib import pyplot as plt
img = io.imread('E:\\histogram.png')
img_rescaled = rescale(img, scale=(0.25), multichannel=True)

io.imshow(img)
io.show()
io.imshow(img_rescaled)
io.show()

Rotate an Image by Different Angles

To fix this orientation problem, we will need to rotate the image by a certain angle. We can use
the rotate function of skimage and specify the angle by which we need the image to be rotated.

Example:
from skimage.transform import rotate
from skimage import io
from matplotlib import pyplot as plt
img = io.imread('E:\\histogram.png')
img_rotate = rotate(img, angle=90)

io.imshow(img)
io.show()
io.imshow(img_rotate)
io.show()

4
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
After executing the above code, if you look closely, the picture is cropped around the corners.
This is because, during the rotation, the size of the image remains the same causing the area
around the corner to get cropped. This can be avoided by the resize parameter in
the rotate function (by default the parameter value is False).

Example:

from skimage.transform import rotate


from skimage import io
from matplotlib import pyplot as plt
img = io.imread('E:\\histogram.png')
img_rotate = rotate(img, angle=45, resize=True)

io.imshow(img)
io.show()
io.imshow(img_rotate)
io.show()

Flip Images Horizontally and Vertically

We can flip an image both horizontally and vertically. This creates a mirror image along the
horizontal/vertical axis. We can use this technique for both image preprocessing and image
augmentation. Although there is no direct function for this in skimage, we can use NumPy to
perform this task. NumPy provides functions flipud (flip up direction) and fliplr (flip left to
right) for flipping the images in horizontal and vertical axis.

Example:

from skimage import io


from numpy import fliplr, flipud
img = io.imread('E:\\histogram.png')
img_2 = io.imread('E:\\car.jpg')

flip_lr = fliplr(img_2)
flip_ud = flipud(img)

io.imshow(img_2)
io.show()
io.imshow(flip_lr)
io.show()

io.imshow(img)
io.show()
io.imshow(flip_ud)
io.show()

Crop Images

5
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
We crop images to remove the unwanted portion of the image or to focus on a particular part of
the image.

Example:

from skimage import io


img = io.imread('E:\\histogram.png')

# selecting part of the image only


cropped = img[100:(img.shape[0]-200),100:(img.shape[1]-200)]
io.imshow(cropped)
io.show()

Changing Image Brightness

Images with different brightness can be used to make computer vision model robust to changes
in lighting conditions. The brightness of images can be changed using the adjust_gamma 
function in skimage, which uses a method called gamma correlation. For any given image, the
pixel values are first normalized between 0 – 1 and then multiplied by a specified gamma value.
The resulting pixel values are scaled back to the range 0-255. For gamma greater than 1, the
output image will be darker than the input image. While for gamma less than 1, the output image
will be brighter than the input image.

Example:

from skimage import exposure


from skimage import io
img = io.imread('E:\\histogram.png')
image_bright = exposure.adjust_gamma(img, gamma=0.5,gain=1)
image_dark = exposure.adjust_gamma(img, gamma=1.5,gain=1)

io.imshow(img)
io.show()
io.imshow(image_bright)
io.show()
io.imshow(image_dark)
io.show()

Image filtering

Filtering is one of the most basic and common image operations in image processing. You can
filter an image to remove noise, modify or enhance features. Filters can also be used for various
purposes, such as smoothing and sharpening the image, highlighting features and edges in the
image, etc. The filtered image could be the desired result or just a preprocessing step. When we
apply a filter on an image, every pixel value is replaced by a new value generated using
surrounding pixel values. These surrounding elements are identified or weighted based on a
"structuring element", or "kernel".

6
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
The simplest filter is the median filter, where the pixel values are replaced with the median of
neighboring pixels.

Example:

from skimage.filters import gaussian, median


from skimage import io
img = io.imread('E:\\car.jpg', as_gray=False)
image_median = median(img, mode='constant', cval=0.5)
#image_median = gaussian(img)

io.imshow(img)
io.show()
io.imshow(image_median)
io.show()

Canny edge detector

Edge detection is done by searching for pixels which have sharp change in intensity or color.
The Canny filter is a multi-stage edge detector. Canny algorithm applies a Gaussian filter with
the default sigma value of 1 to remove the noise from an image before detecting edges. The
following example applies two sigma values; one with the default value of 1 and one with the
value of 3. Smaller sigma value means removing less details yielding to more edges being shown
in the end result.

Example:
from skimage import feature
from skimage import io
import matplotlib.pyplot as plt

img = io.imread('E:\\car.jpg', as_gray=True)


edges1 = feature.canny(img, sigma=1)
edges2 = feature.canny(img, sigma=3)

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),


sharex=True, sharey=True)

ax1.imshow(img, cmap=plt.cm.gray)
ax1.axis('off')
ax1.set_title('Original image', fontsize=16)

ax2.imshow(edges1, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('Canny filter, sigma=1', fontsize=16)

ax3.imshow(edges2, cmap=plt.cm.gray)
ax3.axis('off')

7
DEPARTMENT OF INFORMATION TECHNOLOGY, QUEST NAWABSHAH
DIGITAL IMAGE PROCESSING, 19 BS(IT) BATCH
ax3.set_title('Canny filter, sigma=3', fontsize=16)

fig.tight_layout()
plt.show()

You might also like