Scikit learn Image Processing

In this Python tutorial, we will learn about Scikit learn image, and we will also cover different examples related to Scikit learn image. And, we will cover these topics.

  • Scikit learn image similarity
  • Scikit learn image clustering
  • Scikit learn image augmentation
  • Scikit learn image dataset
  • Scikit learn image preprocessing
  • Scikit learn image feature extraction
  • Scikit-learn image classification
  • Scikit learn image segmentation
  • Scikit learn image recognition
  • Scikit learn image install
  • Scikit learn image read image

Scikit learn image similarity

In this section, we will learn about how scikit learn image similarity works using python.

Scikit learn image similarity is defined as a process from which estimates the similarity of the two same images.

Code:

In the following code, we will import structural_similarity as ssim from skimage.metrics by which we can estimate the similarity of the images.

  • image = img_as_float(data.camera()) is use to take an example for running the image.
  • range = num.random.default_rng() is used to generate the random default range.
  • image_noise = image + noise is used to add the noise with the image.
  • fig, axes = plot.subplots(nrows=1, ncols=3, figsize=(10, 4),sharex=True, sharey=True) is used to plot the image on the screen.
  • mse_none = mean_squared_error(image, image) is used to show the similarity in the images.
  • axis[0].imshow(image, cmap=plot.cm.gray, vmin=0, vmax=1) is used to show the axison the screen.
  • axis[0].set_xlabel(f’MSE: {mse_none:.2f}, SSIM: {ssim_none:.2f}’) is used to give the x label to the axis.
  • axis[0].set_title(‘Original image’) is used to give the title to the image.
import numpy as num
import matplotlib.pyplot as plot

from skimage import data, img_as_float
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import mean_squared_error


image = img_as_float(data.camera())
rows, cols = image.shape

noise = num.ones_like(image) * 0.3 * (image.max() - image.min())
range = num.random.default_rng()
noise[range.random(size=noise.shape) > 0.6] *= -1

image_noise = image + noise
image_const = image + abs(noise)

fig, axes = plot.subplots(nrows=1, ncols=3, figsize=(10, 4),
                         sharex=True, sharey=True)
axis = axes.ravel()

mse_none = mean_squared_error(image, image)
ssim_none = ssim(image, image, data_range=image.max() - image.min())

mse_noise = mean_squared_error(image, image_noise)
ssim_noise = ssim(image, image_noise,
                  data_range=image_noise.max() - image_noise.min())

mse_const = mean_squared_error(image, image_const)
ssim_const = ssim(image, image_const,
                  data_range=image_const.max() - image_const.min())

axis[0].imshow(image, cmap=plot.cm.gray, vmin=0, vmax=1)
axis[0].set_xlabel(f'MSE: {mse_none:.2f}, SSIM: {ssim_none:.2f}')
axis[0].set_title('Original image')

axis[1].imshow(image_noise, cmap=plot.cm.gray, vmin=0, vmax=1)
axis[1].set_xlabel(f'MSE: {mse_noise:.2f}, SSIM: {ssim_noise:.2f}')
axis[1].set_title('Image with noise')

axis[2].imshow(img_const, cmap=plot.cm.gray, vmin=0, vmax=1)
axis[2].set_xlabel(f'MSE: {mse_const:.2f}, SSIM: {ssim_const:.2f}')
axis[2].set_title('Image plus constant')

plot.tight_layout()
plot.show()

Output:

After running the above code, we get the following output. In the output, we can see that the scikit learn image similarity is shown on the screen.

scikit learn image similarity
scikit learn image similarity

Read: Scikit learn Hidden Markov Model

Scikit learn image clustering

In this section, we will learn about scikit learn image clustering works in python.

  • Clustering is defined as grouping the unlabeled dataset or grouping the data into different clusters which have similar data points.
  • Here we use spectral clustering which is used to cut the graph and minimize the ratio of the gradient.

Code:

In the following code, we will import spectral_clustering from sklearn.cluster by which we can cut the graph and minimize the ratio of the gradient.

  • x, y = np.indices((l, l)) is used to return the array representing the indices of a grid.
  • imge = circle1 + circle2 + circle3 + circle4 is used to created the four circles.
  • mask = imge.astype(bool) is used to limit the foreground.
  • graph = image.img_to_graph(imge, mask=mask) is used convert the image into graph with value of gradient on the edges.
  • label_im = num.full(mask.shape, -1.0) is used to give the full shape to the graph.
  • plot.matshow(imge) is used to plot the image.
  • labels = spectral_clustering(graph, n_clusters=2, eigen_solver=”arpack”) is used to minimise the ratio of the gradient.
import numpy as num
import matplotlib.pyplot as plot

from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering

l = 100
x, y = np.indices((l, l))

center1 = (29, 25)
center2 = (41, 51)
center3 = (68, 59)
center4 = (25, 71)

radius1, radius2, radius3, radius4 = 17, 15, 16, 15

circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2
circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2



imge = circle1 + circle2 + circle3 + circle4


mask = imge.astype(bool)

imge = imge.astype(float)
imge += 1 + 0.2 * num.random.randn(*imge.shape)


graph = image.img_to_graph(imge, mask=mask)


graph.data = num.exp(-graph.data / graph.data.std())


labels = spectral_clustering(graph, n_clusters=4, eigen_solver="arpack")
label_im = num.full(mask.shape, -1.0)
label_im[mask] = labels

plot.matshow(imge)
plot.matshow(label_im)



imge = circle1 + circle2
mask = imge.astype(bool)
imge = imge.astype(float)

imge += 1 + 0.2 * num.random.randn(*imge.shape)

graph = image.img_to_graph(imge, mask=mask)
graph.data = num.exp(-graph.data / graph.data.std())

labels = spectral_clustering(graph, n_clusters=2, eigen_solver="arpack")
label_im = num.full(mask.shape, -1.0)
label_im[mask] = labels

plot.matshow(imge)
plot.matshow(label_im)

plot.show()

Output:

After running the above code, we get the following output in which we can see that the scikit learn image clustering is performed on the screen.

scikit learn image clustering
scikit learn image clustering

Also, check: Scikit learn Hierarchical Clustering

Scikit learn image augmentation

In this section, we will learn about how scikit learn image augmentation works in python.

Image augmentation is defined as a technique that is used to increase the size of our image and is also done by the transformation of the image.

Code:

In the following code, we will import some libraries from which we can do the augmentation of the image.

  • figure = plot.figure(tight_layout=’auto’, figsize=(10, 7)) is used to plot the figure on the screen.
  • imge = imread(‘buterfly.jpg’) / 255 is used to load the image.
  • plot.imshow(img) is used to plot the original image.
from skimage import transform
from skimage.transform import rotate, AffineTransform,warp
from skimage.util import random_noise
from skimage.filters import gaussian
from scipy import ndimage
import random
from skimage import img_as_ubyte
import os
#basic Function to display image side by side
def plotsides(imge1, imge2, title1, title2, cmap = None):
    figure = plot.figure(tight_layout='auto', figsize=(10, 7))
    figure.add_subplot(221)
    plot.title(title1)
    plot.imshow(imge)
    figure.add_subplot(222)
    plot.title(title2)
    plot.imshow(imge2, cmap = None)
    return fig

imge = imread('buterfly.jpg') / 255

plot.imshow(img)
plot.title('Original')
plot.show()
scikit learn augmentation original image
scikit learn augmentation original image
  • rotate30 = rotate(imge, angle=30) is used to rotate the image at the angle of 30.
  • rotate45 = rotate(imge, angle=45) is used to rotate the image at the angle of 45.
  • rotate60 = rotate(imge, angle=60) is used to rotate the image at the angle of 60.
  • rotate90 = rotate(imge, angle=90) is used to rotate the image at the angle of 90.
  • figure = plot.figure(tight_layout=’auto’, figsize=(10, 10)) is used to plot all the figure on the screen.
  • plot.title(‘Rotate 30’) is used to give the title to the screen.
rotate30 = rotate(imge, angle=30)
rotate45 = rotate(imge, angle=45)
rotate60 = rotate(imge, angle=60)
rotate90 = rotate(imge, angle=90)
figure = plot.figure(tight_layout='auto', figsize=(10, 10))
figure.add_subplot(221)
plot.title('Rotate 30')
plot.imshow(rotate30)
figure.add_subplot(222)
plot.title('Rotate 45')
plot.imshow(rotate45)
figure.add_subplot(223)
plot.title('Rotate 60')
plot.imshow(rotate60)
figure.add_subplot(224)
plot.title('Rotate 90')
plot.imshow(rotate90)
plot.show()
scikit learn augmentation rotation images
scikit learn augmentation rotation images
  • Here, sheared = transform.warp(img, tf, order=1, preserve_range=True, mode=’wrap’) is used to transform the image original to sheared.
tf = AffineTransform(shear=-0.5)
sheared = transform.warp(img, tf, order=1, preserve_range=True, mode='wrap')
sheared_figure = plot_side(img, sheared, 'Original', 'Sheared')
scikit learn augmentation sheared image
scikit learn augmentation sheared image
  • Here, warp_images = warp(imge,transform, mode=”wrap”) is to wrap the image.
  • Here, warp_figure = plot_side(imge,warp_images , ‘Original’, ‘Wrap images’) is used to plot the figures on the screen.

transform = AffineTransform(translation=(-200,0)) 
 
warp_images = warp(imge,transform, mode="wrap") 

warp_figure = plot_side(imge,warp_images , 'Original', 'Wrap images')
scikit learn image augmentation transformation
scikit learn image augmentation transformation

Now, the noise_figure = plot_side(imge,noisy_images , ‘Original’, ‘Noise_image’) is used to create and plot the noisy image.


noisy_images = random_noise(imge, var=0.1**.01)
noise_figure = plot_side(imge,noisy_images , 'Original', 'Noise_image')
scikit learn augmentation noisy image
scikit learn augmentation noisy image
  • blured_images = ndimage.uniform_filter(imge, size=(11, 11, 1)) is used to make the blurry image.
  • noise_figure = plot_side(imge,blured_images , ‘Original’, ‘Blurred’) is used to plot the image on the screen.

from scipy import ndimage
blured_images = ndimage.uniform_filter(imge, size=(11, 11, 1))
noise_figure = plot_side(imge,blured_images , 'Original', 'Blurred')
scikit learn image augmentation blurring
scikit learn image augmentation blurring
  • highBrightness = imge + (100/255) is used to increase the brightness of the image.
  • figure_highBrightness = plot_side(imge, highBrightness, ‘Original’, ‘Brightened’) is used to plot the image on the screen.

highBrightness = imge + (100/255)
figure_highBrightness = plot_side(imge, highBrightness, 'Original', 'Brightened')
plot.show()
scikit learn image augmentation increasing brightness
scikit learn image augmentation increasing brightness
  • up_down = np.flipud(imge) is used to flip the image up and down.
  • figure_updown = plot_side(imge, up_down, ‘Original’, ‘Up-Down’) is used to plot the figure on the screen.
# flip up-down using np.flipud
up_down = np.flipud(imge)
figure_updown = plot_side(imge, up_down, 'Original', 'Up-Down')
plot.show()
scikit learn image augmentation flipping up down
scikit learn image augmentation flipping up down

Read: Scikit learn Classification Tutorial

Scikit learn image dataset

In this section, we will learn about how Scikit learn image dataset work in python.

An image dataset is defined as which stores the data of the image in the data container and returns the result by the many algorithms.

Code:

In the following code, we will import load_sample_images from sklearn.datasets by which we can load the image with the help of data.

  • len(datasets.images) is used to get the length of the image.
  • first_imge_data.shape is used to get the shape of the image.
from sklearn.datasets import load_sample_images
datasets = load_sample_images()     
len(datasets.images)
first_imge_data = dataset.images[0] 
first_imge_data.shape 
scikit learn image dataset
scikit learn image dataset

first_imge_data.dtype is used to get the type of the data.

first_imge_data.dtype 
scikit learn image dataset type
scikit learn image dataset type

Read: Scikit learn Hyperparameter Tuning

Scikit learn image preprocessing

In this section, we will learn about how scikit learn image preprocessing works in python.

Image preprocessing is defined as a step in which the image is taken to formate before being used by model training.

Code:

In the following code, we will import io from sklearn for preprocessing the image.

  • First, files = os.path.join( ‘ladybug.jpg’) is used to load the image.
  • Second, io.imshow(ladybug) is used to show the input image.
import os

import skimage
from skimage import io
  

files = os.path.join( 'ladybug.jpg')

  
ladybug = io.imread(files)

io.imshow(ladybug)
io.show()

Output:

After running the above code, we get the following output. In the output, we can see that Scikit learn image preprocessing is done on the screen.

scikit learn image preprocessing
scikit learn image preprocessing

Read: Scikit learn hidden_layer_sizes

Scikit learn image feature extraction

In this section, we will learn how scikit learn image feature extraction works in python.

  • Image feature extraction as the name defines extracts features from the image. Feature extraction is related to dimension reduction.
  • Feature extraction is also defined as reducing the number of resources which can easily describe the large number of data.

Code:

In the following code, we will use imread.imshow from skimage.io by which we can run the image.

In the code, image1 = imread(‘grasshopper.jpg’) is used to load the image.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from skimage.io import imread, imshow
image1 = imread('grasshopper.jpg')
imshow(image1);
scikit learn feature extraction original image
scikit learn feature extraction original image

Also, image2 = imread(‘grasshopper.jpg’, as_gray=True) is used to load the grey shade image.

image2 = imread('grasshopper.jpg', as_gray=True)
imshow(image2);
scikit learn feature extraction grey scale image
scikit learn feature extraction greyscale image
  • print(image1.shape) is used to print the shape of the image1.
  • print(image2.shape) is used to print the shape of image2.
print(image1.shape)
print(image2.shape)
scikit learn image feature extraction shape
scikit learn image feature extraction shape
  • print(image1.size) is used to print the size of the image1.
  • print(image2.size) is used to print the size of the image2.
print(image1.size)
print(image2.size)
scikit learn image feature extraction size
scikit learn image feature extraction size

Here, feature2 = np.reshape(image2, (280 * 390 )) is used to find the feature reshaping the shape of image2 and returning the array.

feature2 = np.reshape(image2, (280 * 390 ))
feature2
scikit learn image feature extraction gray scale
scikit learn image feature extraction grayscale

And feature1 = np.reshape(image1, (280 * 390 * 3)) is used to find the feature reshaping the shape of image1 and returning the array.

feature1 = np.reshape(image1, (280 * 390 * 3))
feature1
scikit learn image feature extraction original
scikit learn image feature extraction original

Read: Scikit learn Linear Regression + Examples

Scikit learn image classification

In this section, we will learn about how scikit learn image classification works in python.

Image classification is defined as a process in which the image is classified into its different category classes.

Code:

In the following code, we will import some libraries for which we can classify the image.

  • clfdata[‘description’] = ‘resized ({0}x{1})animal images in rgb’.format(int(width), int(height)) is used to give the description of data.
  • current_path = os.path.join(src, subdir) is used to read the images from the path and resize the images to the destination path.
  • clfdata_path = ‘/content/drive/MyDrive/Image’ is used the path of my drive.
import matplotlib.pyplot as plot
import numpy as num
import os
import pprint
pp = pprint.PrettyPrinter(indent=4)
import joblib
from skimage.io import imread
from skimage.transform import resize
 
def resize_all(src, pklname, include, width=150, height=None):
 
    height = height if height is not None else width
     
    clfdata = dict()
    clfdata['description'] = 'resized ({0}x{1})animal images in rgb'.format(int(width), int(height))
    clfdata['label'] = []
    clfdata['filename'] = []
    clfdata['data'] = []   
     
    pklname = f"{pklname}_{width}x{height}px.pkl"

    for subdir in os.listdir(src):
        if subdir in include:
            print(subdir)
            current_path = os.path.join(src, subdir)
 
            for file in os.listdir(current_path):
                if file[-3:] in {'jpg', 'png'}:
                    im = imread(os.path.join(current_path, file))
                    im = resize(im, (width, height)) 
                    clfdata['label'].append(subdir[:-4])
                    clfdata['filename'].append(file)
                    clfdata['data'].append(im)
 
        joblib.dump(clfdata, pklname)
clfdata_path = '/content/drive/MyDrive/Image'
os.listdir(clfdata_path)

Output:

After running the above code, we get the following output in which we can see that the animal dataset is printed on the screen.

scikit learn image classification dataset
scikit learn image classification dataset
  • basename = ‘animal_faces’ is used as a name of the dataset.
  • resize_all(src=clfdata_path, pklname=basename, width=width, include=include) is used to resize the dataset.
basename = 'animal_faces'
width = 80
 
include = {'ChickenHead', 'BearHead', 'ElephantHead', 
           'EagleHead', 'DeerHead', 'MonkeyHead', 'PandaHead'}
 
resize_all(src=clfdata_path, pklname=basename, width=width, include=include)
scikit learn image classification resizes dataset
scikit learn image classification resizes dataset
  • clfdata = joblib.load(f'{basename}_{width}x{width}px.pkl’) is used to load the dataset.
  • print(‘number of samples: ‘, len(clfdata[‘data’])) is used to print the number of samples.
  • print(‘keys: ‘, list(clfdata.keys())) is used to print the number of keys.
  • print(‘image shape: ‘, clfdata[‘data’][0].shape) is used to print the shape of image.
  • print(‘labels:’, num.unique(clfdata[‘label’])) is used to print the labels.
  • Counter(clfdata[‘label’]) is used to print the counter.
from collections import Counter
 
clfdata = joblib.load(f'{basename}_{width}x{width}px.pkl')
 
print('number of samples: ', len(clfdata['data']))
print('keys: ', list(clfdata.keys()))
print('description: ', clfdata['description'])
print('image shape: ', clfdata['data'][0].shape)
print('labels:', num.unique(clfdata['label']))
 
Counter(clfdata['label'])
scikit learn image classification counter data
scikit learn image classification counter data
  • labels = num.unique(clfdata[‘label’]) is used to get all unique values in the list of labels.
  • figure, axes = plot.subplots(1, len(labels)) are used to set up the matplotlib figure and axes based on the number of labels.
  • idx = clfdata[‘label’].index(label) is used to get the index of the first item corresponding to its search string.

labels = num.unique(clfdata['label'])
 

figure, axes = plot.subplots(1, len(labels))
figure.set_size_inches(17,6)
figure.tight_layout()
 
 

for axis, label in zip(axes, labels):
    idx = clfdata['label'].index(label)
     
    axis.imshow(clfdata['data'][idx])
    axis.axis('off')
    axis.set_title(label)
scikit learn image classification
scikit learn image classification
  • x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4,shuffle=True,random_state=44, ) is used to split the dataset into train data and test data.
  • unique, counts = num.unique(y, return_counts=True) is used to calculate court per type.
  • counts = 100*counts[sorted_index]/len(y) is used to ployt as a percent.
  • counts = counts[sorted_index] is used to plot as a count.
  • plot.xticks(xtemp, unique, rotation=45) is used to plot the x ticks.
  • plot.suptitle(‘relative amount of photos per type’) is used to plot the subtitle on the screen.
  • plot_bar(y_train, loc=’left’) is used to plot the y_train bars on the screen.
  • plot_bar(y_test, loc=’right’) is used to plot the y_test bars on the screen.
x = num.array(clfdata['data'])
y = num.array(clfdata['label'])
from sklearn.model_selection import train_test_split
 
x_train, x_test, y_train, y_test = train_test_split(
    x, 
    y, 
    test_size=0.4, 
    shuffle=True,
    random_state=44,
)
def plot_bar(y, loc='left', relative=True):
    width = 0.37
    if loc == 'left':
        n = -0.7
    elif loc == 'right':
        n = 0.7
     

    unique, counts = num.unique(y, return_counts=True)
    sorted_index = num.argsort(unique)
    unique = unique[sorted_index]
     
    if relative:

        counts = 100*counts[sorted_index]/len(y)
        ylabel_text = '% count'
    else:

        counts = counts[sorted_index]
        ylabel_text = 'count'
         
    xtemp = num.arange(len(unique))
     
    plot.bar(xtemp + n*width, counts, align='center', alpha=.7, width=width)
    plot.xticks(xtemp, unique, rotation=45)
    plot.xlabel('equipment type')
    plot.ylabel(ylabel_text)
 
plot.suptitle('relative amount of photos per type')
plot_bar(y_train, loc='left')
plot_bar(y_test, loc='right')
plot.legend([
    'train ({0} photos)'.format(len(y_train)), 
    'test ({0} photos)'.format(len(y_test))
]);
scikit learn image classification graph
scikit learn image classification graph

Read: Scikit learn Feature Selection

Scikit learn image segmentation

In this section, we will learn about how scikit learn image segmentation works in python.

Scikit learn image segmentation is defined as an algorithm that balances the volume of the circle. If all the circle is of the same size segmentation works perfectly if the size is different segmentation fails.

Code:

  • x, y = np.indices((l, l)) is used to return the array representing the indices of a grid.
  • imge = circle1 + circle2 + circle3 + circle4 is used to created the four circles.
  • mask = imge.astype(bool) is used to limit the foreground.
  • graph = image.img_to_graph(imge, mask=mask) is used convert the image into graph with value of gradient on the edges.
  • label_im = num.full(mask.shape, -1.0) is used to give the full shape to the graph.
  • plot.matshow(imge) is used to plot the image.
  • labels = spectral_clustering(graph, n_clusters=2, eigen_solver=”arpack”) is used to minimise the ratio of the gradient.
import numpy as num
import matplotlib.pyplot as plot

from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering

l = 100
x, y = num.indices((l, l))

center1 = (27, 23)
center2 = (39, 49)
center3 = (66, 57)
center4 = (23, 69)

radius1, radius2, radius3, radius4 = 15, 13, 14, 13

circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2
circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2


imge = circle1 + circle2 + circle3 + circle4


mask = imge.astype(bool)

imge = imge.astype(float)
imge += 2 + 0.3 * num.random.randn(*imge.shape)


graph = image.img_to_graph(imge, mask=mask)


graph.data = num.exp(-graph.data / graph.data.std())


labels = spectral_clustering(graph, n_clusters=4, eigen_solver="arpack")
label_im = num.full(mask.shape, -4.0)
label_im[mask] = labels

plot.matshow(imge)
plot.matshow(label_im)


imge = circle1 + circle2+circle3
mask = imge.astype(bool)
imge = imge.astype(float)

imge += 2 + 0.3 * num.random.randn(*imge.shape)

graph = image.img_to_graph(imge, mask=mask)
graph.data = num.exp(-graph.data / graph.data.std())

labels = spectral_clustering(graph, n_clusters=2, eigen_solver="arpack")
label_im = num.full(mask.shape, -2.0)
label_im[mask] = labels

plot.matshow(imge)
plot.matshow(label_im)

plot.show()

Output:

After running the above code, we get the following output in which we can see that the size and shape of the circle are the same, the segmentation never fails.

scikit learn image segmentation
scikit learn image segmentation

Read: Scikit learn Ridge Regression

Scikit learn image recognition

In this section, we will learn about how Scikit learn image recognition works in python.

The Scikit learn image recognition is a process for recognizing the image and is also used to identify the objects.

Code:

In the following code, we will import some libraries from which we can recognize the image.

  • dog = rescale(dog, 1/3, mode=’reflect’) is used to scale down the image to one third.
  • dog_hog, dog_hog_img = hog(dog, pixels_per_cell=(14,14),cells_per_block=(2, 2), orientations=9,visualize=True,block_norm=’L2-Hys’) is used to calculate the hog and return a visual representation.
  • a.tick_params(bottom=False, left=False, labelbottom=False, labelleft=False) is used to remove their ticks and labels.
  • axis[0].set_title(‘dog’) is used to give the title to the image.
from skimage.feature import hog
from skimage.io import imread
from skimage.transform import rescale
import matplotlib.pyplot as plot
 
dog = imread('dog.jpg', as_gray=True)


dog = rescale(dog, 1/3, mode='reflect')

dog_hog, dog_hog_img = hog(
    dog, pixels_per_cell=(14,14), 
    cells_per_block=(2, 2), 
    orientations=9, 
    visualize=True, 
    block_norm='L2-Hys')
 
figure, axis = plot.subplots(1,2)
figure.set_size_inches(8,6)

[a.tick_params(bottom=False, left=False, labelbottom=False, labelleft=False) 
    for a in axis]
 
axis[0].imshow(dog, cmap='gray')
axis[0].set_title('dog')
axis[1].imshow(dog_hog_img, cmap='gray')
axis[1].set_title('hog')
plot.show()

Output:

After running the above code, we get the following output in which we can recognize the image of a dog.

scikit learn image recognition
scikit learn image recognition

From this code, we can see that some of the data points are reduced which is processed in our model. And after some imagination, we can recognize the dog.

print('number of pixels: ', dog.shape[0] * dog.shape[1])
print('number of hog features: ', dog_hog.shape[0])
scikit learn image recognition percentage
scikit learn image recognition percentage

Read: Scikit learn Decision Tree

Scikit learn image install

In this section, we will learn about how scikit learn image to install in python.

If we want to install the scikit learn image then firstly check the scikit-image is already installed or it works or not and check the installation version.

We can check the scikit-image version or its working by the following command:

import skimage
print(skimage.__version__)
scikit learn install image check version
scikit learn install image check version

If we want to update the version or install it again then use this command:

 pip  install -U scikit-image

We have already installed the updated version of the scikit-image as shown in the picture.

scikit learn install image update version
scikit learn install image update version

Read: Scikit-learn Vs Tensorflow

Scikit learn image read image

In this section, we will learn about how scikit learn image read image works in python.

Scikit learn image read image function is used to read or process the image. We can also read the image with the help of the scikit-image module.

Code:

In the following code, we will import some libraries from which we can read an image and process the image.

In the code, image_gray = imread(‘player.jpg’, as_gray=True) is used to read the gray image and load on the screen.

from skimage.io import imread, imshow
import matplotlib.pyplot as plt
%matplotlib inline

image_gray = imread('player.jpg', as_gray=True)
imshow(image_gray)
scikit learn image read image
scikit learn image read image
  • print(image_gray.shape) is used to print the shape of the gray image.
image_gray = imread('player.jpg', as_gray=True)
print(image_gray.shape)
print(image_gray)
scikit learn image read image gray shape
scikit learn image read image gray shape
  • image_color = imread(‘player.jpg’, as_gray=False) is used to load and read the colored image on the screen.
  • print(image_color.shape) is used to print the colored image shape on the screen.
from skimage.io import imread, imshow
import matplotlib.pyplot as plt
%matplotlib inline

image_color = imread('player.jpg', as_gray=False)
print(image_color.shape)
imshow(image_color)
scikit learn image read image color shape
scikit learn image read image color shape

Also, take a look at some more Scikit learn tutorials.

So, in this tutorial, we discussed Scikit learn image and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.

  • Scikit learn image similarity
  • Scikit learn image clustering
  • Scikit learn image augmentation
  • Scikit learn image dataset
  • Scikit learn image preprocessing
  • Scikit learn image feature extraction
  • Scikit-learn image classification
  • Scikit learn image segmentation
  • Scikit learn image recognition
  • Scikit learn image install
  • Scikit learn image read image