0% found this document useful (0 votes)
7 views20 pages

Wa0005

The document contains a series of Python programs that demonstrate various image processing techniques using libraries such as NumPy, Matplotlib, and scikit-image. These techniques include creating a checkerboard image, reading and displaying images, applying Otsu thresholding, Sobel filtering, extracting color channels, and performing transformations like log and gamma correction. Additionally, the document covers edge detection, convolution, and denoising methods, providing a comprehensive overview of image manipulation and analysis.

Uploaded by

SRINIVAS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views20 pages

Wa0005

The document contains a series of Python programs that demonstrate various image processing techniques using libraries such as NumPy, Matplotlib, and scikit-image. These techniques include creating a checkerboard image, reading and displaying images, applying Otsu thresholding, Sobel filtering, extracting color channels, and performing transformations like log and gamma correction. Additionally, the document covers edge detection, convolution, and denoising methods, providing a comprehensive overview of image manipulation and analysis.

Uploaded by

SRINIVAS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

/*1. Write a program to create an checkboard image.

*/

import numpy as np

import matplotlib.pyplot as plt

check = np.zeros((9, 9))

check[::2, 1::2] = 1

check[1::2, ::2] = 1

plt.matshow(check, cmap='gray')

plt.show()

Output:-
/*2. Write a program to read and display the image.*/

import matplotlib.pyplot as plt

from skimage import data

camera = data.camera()

plt.figure(figsize=(4, 4))

plt.imshow(camera, cmap='gray', interpolation='nearest')

plt.axis('off')

plt.tight_layout()

plt.show()

Output:-
/*3. Write a program for Otsu threshold.*/

from skimage import data

from skimage import filters

import matplotlib.pyplot as plt

camera = data.camera()

plt.imshow(camera)

val = filters.threshold_otsu(camera)

mask = camera < val

plt.imshow(mask)

Output:-
/*4. Write a program to filter the image using a Sobel filter.*/

from skimage import data

from skimage import filters

import matplotlib.pyplot as plt

text = data.text()

hsobel_text = filters.sobel_h(text)

plt.figure(figsize=(12, 3))

plt.subplot(121)

plt.imshow(text, cmap='gray', interpolation='nearest')

plt.axis('off')

plt.subplot(122)

plt.imshow(hsobel_text, cmap='spectral', interpolation='nearest')

plt.axis('off')

Output:-
/*5. Write a program to extract the Hue and Value channels from Color
image..*/

import matplotlib.pyplot as plt

from skimage import data

from skimage.color import rgb2hsv

rgb_img = data.astronaut()

hsv_img = rgb2hsv(rgb_img)

hue_img = hsv_img[:, :, 0]

value_img = hsv_img[:, :, 2]

fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(8, 2))

ax0.imshow(rgb_img)

ax0.set_title("RGB image")

ax0.axis('off')

ax1.imshow(hue_img, cmap='hsv')

ax1.set_title("Hue channel")

ax1.axis('off')

ax2.imshow(value_img)

ax2.set_title("Value channel")

ax2.axis('off')

fig.tight_layout()

hue_threshold = 0.06

binary_img = hue_img > hue_threshold


fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(8, 3))ax0.hist(hue_img.ravel(),
512)

ax0.set_title("Histogram of the Hue channel with threshold")

ax0.axvline(x=hue_threshold, color='r', linestyle='dashed', linewidth=2)

ax0.set_xbound(0, 0.12)

ax1.imshow(binary_img)

ax1.set_title("Hue-thresholded image")

ax1.axis('off')

fig.tight_layout()

Output:-
/*6. Write a program to perform the log transformation on the image.*/

import imageio

import numpy as np

import matplotlib.pyplot as plt

pic = imageio.imread('E:\codes\parrot.png')

gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114])

gray = gray(pic)

'''

log transform

-> s = c*log(1+r)

So, we calculate constant c to estimate s

-> c = (L-1)/log(1+|I_max|)

'''

max_ = np.max(gray)

def log_transform():

return (255/np.log(1+max_)) * np.log(1+gray)

plt.figure(figsize = (5,5))

plt.imshow(log_transform(), cmap = plt.get_cmap(name = 'gray'))

plt.axis('off');
Output:-
/*7. Write a program to perform an intensity transformation on the im-
age.*/

import imageio

import matplotlib.pyplot as plt

import warnings

import matplotlib.cbook

warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)

pic = imageio.imread('E:\codes\parrot.png')

plt.figure(figsize = (6,6))

plt.imshow(pic);

plt.axis('off');

negative = 100 - pic # neg = (L-1) - img

plt.figure(figsize = (6,6))

plt.imshow(negative)

plt.axis('off');
Output:-
/*8. Write a program to perform the gamma correction on the image.*/

import imageio

import matplotlib.pyplot as plt

# Gamma encoding

pic = imageio.imread('E:\codes\parrot.png')

plt.imshow(pic)

gamma = 2.2 # Gamma < 1 ~ Dark ; Gamma > 1 ~ Bright

gamma_correction = ((pic/255) ** (1/gamma))

plt.figure(figsize = (5,5))

plt.imshow(gamma_correction)

plt.axis('off');

Output:-
/*9. Write a program to detect the highest pixel values from the input im-
age.*/

pic=imageio.imread('E:\codes\purple.png')

plt.imshow(pic)

plt.axis('off');

red_mask=pic[:,:,0]<180

pic[red_mask]=0

plt.figure(figsize=(15,15))

plt.imshow(pic)

plt.axis('off');

# Only Green Pixel value , higher than 180

pic=imageio.imread('E:\codes\purple.png')

green_mask=pic[:,:,1]<180

pic[green_mask]=0

plt.figure(figsize=(15,15))

plt.imshow(pic)

plt.axis('off');

# Only Blue Pixel value , higher than 180

pic=imageio.imread('E:\codes\purple.png')

blue_mask=pic[:,:,2]<180

pic[blue_mask]=0

plt.figure(figsize=(15,15))

plt.imshow(pic)
plt.axis('off');

# Composite mask using logical_and

pic=imageio.imread('E:\codes\purple.png')

final_mask=np.logical_and(red_mask,green_mask,blue_mask)

pic[final_mask]=40

plt.figure(figsize=(15,15))

plt.imshow(pic)

plt.axis('off');

Output:-
/*10. Write a program to perform the Gaussian, median filter and total
variation denoising from the input.*/

import numpy as np

import matplotlib.pyplot as plt

from skimage import data

from skimage import filters

from skimage import restoration

coins = data.coins()

gaussian_filter_coins = filters.gaussian(coins, sigma=2)

med_filter_coins = filters.median(coins, np.ones((3, 3)))

tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1)

plt.figure(figsize=(16, 4))

plt.subplot(141)

plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest')

plt.axis('off')

plt.title('Image')

plt.subplot(142)

plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray',

interpolation='nearest')

plt.axis('off')

plt.title('Gaussian filter')

plt.subplot(143)

plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray',


interpolation='nearest')

plt.axis('off')

plt.title('Median filter')

plt.subplot(144)

plt.imshow(tv_filter_coins[10:80, 300:370], cmap='gray',

interpolation='nearest')

plt.axis('off')

plt.title('TV filter')

plt.show()

Output:-
/*11. Write a program for image convolution.*/

import numpy as np

import imageio

import matplotlib.pyplot as plt

from scipy.signal import convolve2d

def Convolution(image, kernel):

conv_bucket = []

for d in range(image.ndim):

conv_channel = convolve2d(image[:,:,d], kernel,

mode="same", boundary="symm")

conv_bucket.append(conv_channel)

return np.stack(conv_bucket, axis=2).astype("uint8")

kernel_sizes = [9,15,30,60]

fig, axs = plt.subplots(nrows = 1, ncols = len(kernel_sizes), figsize=(15,15));

pic = imageio.imread('F:\python_stuff\codes\parrot.png')

for k, ax in zip(kernel_sizes, axs):

kernel = np.ones((k,k))

kernel /= np.sum(kernel)

ax.imshow(Convolution(pic, kernel));

ax.set_title("Convolved By Kernel: {}".format(k));

ax.set_axis_off();
Output:-
/*12. Write a program to detect the edge of an image using edge kernel
method.*/

from skimage import color

from skimage import exposure

from scipy.signal import convolve2d

import numpy as np

import imageio

import matplotlib.pyplot as plt

pic = imageio.imread('E:\codes\crazycat.png')

# Convert the image to grayscale

img = color.rgb2gray(pic)

# apply sharpen filter to the original image

sharpen_kernel = np.array([[0,-1,0],

[-1,5,-1],

[0,-1,0]])

image_sharpen = convolve2d(img, sharpen_kernel, mode = 'valid')

# apply edge kernel to the output of the sharpen kernel

edge_kernel = np.array([[-1,-1,-1],

[-1,8,-1],

[-1,-1,-1]])

edges = convolve2d(image_sharpen, edge_kernel, mode = 'valid')

# apply normalize box blur filter to the edge detection filtered image

blur_kernel = np.array([[1,1,1],
[1,1,1],

[1,1,1]])/9.0;

denoised = convolve2d(edges, blur_kernel, mode = 'valid')

# Adjust the contrast of the filtered image by applying Histogram Equalization

denoised_equalized =
exposure.equalize_adapthist(denoised/np.max(np.abs(denoised)),

clip_limit=0.03)

plt.figure(figsize = (5,5))

plt.imshow(denoised_equalized, cmap='gray')

plt.axis('off')

plt.show()

Output:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy