0% found this document useful (0 votes)
4K views29 pages

19CS49 Computer Vision Lab File PDF

The document contains programs written in Python for computer vision tasks. Program 1 introduces Python programming and describes what Python is, what it can do, why it is popular, and some key aspects of Python syntax. Program 2 writes a program to display the negative of a digital image by subtracting each pixel value from the maximum pixel value. Program 3 writes a program to perform thresholding on an input image by converting it to a binary black and white image based on a threshold value.

Uploaded by

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

19CS49 Computer Vision Lab File PDF

The document contains programs written in Python for computer vision tasks. Program 1 introduces Python programming and describes what Python is, what it can do, why it is popular, and some key aspects of Python syntax. Program 2 writes a program to display the negative of a digital image by subtracting each pixel value from the maximum pixel value. Program 3 writes a program to perform thresholding on an input image by converting it to a binary black and white image based on a threshold value.

Uploaded by

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

(Deemed to be University under Section 3 of UGC Act, 1956)

COMPUTER VISION LAB


CS-374 C

Nachauli, Old Faridabad-Jasana Road,

Faridabad 121002, Phone: (129) 2201008, 2201009;

WebSite: www.lingayasuniversity.edu.in

SUBMITTED TO:- Submitted by:-G MADHU KUMAR YADAV


VISHAL PRASAD SIR Roll No. 19CS49
S.no List of Programs Date Signature

1) Introduction to python programming

2) Write a Program to display the Negative of a


Digital Image

3) Write a Program to perform thresholding on an


input Image
4) Write a Program to perform gray level slicing
without background
5) Write a Program to perform gray level slicing
with background
6) Write a Program to perform bit-plane slicing

7) Write a Program to display a Histogram of an


image
8) Write a Program to perform Log Transformation
of an image
9) Write a Program to implement an Ideal low pass
filter
10) Write a Program to implement Butterworth low
pass filter

Program-1

AIM:- Introduction to python programming

What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify
files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.

Good to know
• The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.
Python Syntax compared to other programming
languages
• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.

Example
print("Hello, World!")

The number of spaces is up to you as a programmer, the most common use is


four, but it has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!") if 5
> 2: print("Five is greater than
two!")

PROGRAM – 2
Aim:- Write a Program to display the Negative of a Digital Image
Negative of an image in MATLAB:-

The negative of an image is achieved by replacing the intensity 'i' in the original image by 'i-1',
i.e., the darkest pixels will become the brightest and the brightest pixels will become the
darkest. Image negative is produced by subtracting each pixel from the maximum intensity
value.

For example, in an 8-bit grayscale image, the max intensity value is 255, thus each pixel is
subtracted from 255 to produce the output image.

The transformation function used in image negative is :

S = T(r) = (L1) – r
Where L 1 is the max intensity value, - s is the output pixel value and r is the input pixel value

Algorithm

1. Read RGB color image into the MATLAB environment using Matlab inbuilt function
imread()

2. Calculate the levels of the image, for

For example, an 8-bit image has 256 levels

3. Use the formula stated above on every pixel of the image to get the corresponding negative
pixel value.

4. Convert each RGB pixel value at location j) to its negative image values and assign it to the
corresponding location (i, j) of another matrix

5. Display the negative image using MATLAB in-built show() function.

5 with arguments:
PROGRAM – 3
Aim:- Write a Program to perform thresholding on an input Image
Thresholding is a type of image segmentation, where we change the pixels of an image to make the
image easier to analyze. In thresholding, we convert an image from colour or grayscale into a binary
image, i.e., one that is simply black and white. Most frequently, we use thresholding as a way to select
areas of interest of an image, while ignoring the parts we are not concerned with. We have already
done some simple thresholding, in the “Manipulating pixels” section of the Image Representation in
the skimage episode. In that case, we used a simple NumPy array manipulation to separate the pixels
belonging to the root system of a plant from the black background. In this episode, we will learn how
to use skimage functions to perform thresholding. Then, we will use the masks returned by these
functions to select the parts of an image we are interested in.
Next, we would like to apply the threshold t such that pixels with grayscale values on one side
of t will be turned “on”, while pixels with grayscale values on the other side will be turned
“off”. How might we do that? Remember that grayscale images contain pixel values in the
range from 0 to 1, so we are looking for a threshold t in the closed range [0.0, 1.0]. We see in
the image that the geometric shapes are “darker” than the white background but there is also
some light gray noise on the background. One way to determine a “good” value for t is to look
at the grayscale histogram of the image and try to identify what grayscale ranges correspond
to the shapes in the image or the background

PROGRAM-3

AIM: Write a Program to perform gray level slicing without background


PROGRAM-5

AIM: Write a Program to perform gray level slicing with background


import cv2 import numPy as
np # Load the image img =
cv2.imread('test.jpg',0)

# Find width and height of image row,


column = img.shape
# Create an zeros array to store the sliced image img1
= np.zeros((row,column),dtype = 'uint8')
# Specify the min and max range
min_range = 10

max_range = 60
# Loop over the input image and if pixel value lies in desired range set it to 255
otherwise set it to 0. for i in range(row):

for j in range(column):
if img[i,j]>min_range and img[i,j]<max_range: img1[i,j] = 255

q else: img1[i,j] = 0

# Display the image cv2.imshow('sliced


image', img1) cv2.waitKey(0)

PROGRAM-6
AIM: Write a Program to perform bit-plane slicing

import numpy as np import


cv2

#create a image array


img =
cv2.imread("WIN_20170511_13_06_18_Pro.jpg",cv2.IMREAD_GRAYSCALE
)
row ,col = img.shape
#convert each interger pixel value of given image to a bit pixel value of 8-
#bits def
intToBitArray(img) :
list = []

for i in range(row): for j in range(col):


list.append (np.binary_repr( img[i][j] ,width=8 ) )

return list #the binary_repr() fucntion returns binary values but in


#string
#, not integer, which has it's own perk as you will notice

#as variable name says ,it's list of pixel values in binary , but in 1
#dimension
imgIn1D = intToBitArray(img)
#reshaping above 1D array to a matrix aka image
imgIn2D = np.reshape(imgIn1D , (360,640) ) def
bitplane(bitImgVal , img1D ):

'''
this function extracts the specific bit out of each binary pixel values of the
matrix
for example , if bitImgVal = 3 , then , third bit of each pixel is extracted

:param bitImgVal: specifies the position of bit to be extracted


:param img1D: image which is to be compressed
:return: now returns 1 dimensional list of bits
'''
bitList = [ int( i[bitImgVal] ) for i in img1D]

return bitList
#i don't know why but the multiplication factor is : 2^(n-1) where n is the bit
number
#example, if binary pixel value is 11001010 and n = 3 , factor = 2^(3-1)
#image represented by 8th bit plane
eightbitimg = np.array( bitplane(0, imgIn1D ) ) * 128

#image represented by 7th bit plane


sevenbitimg = np.array( bitplane(1,imgIn1D) ) * 64

#bitplane of 8th and 7th bit combine


= eightbitimg + sevenbitimg
comb = np.reshape(combine,(row,col))
#save combined plane image
cv2.imwrite("comb.jpeg",comb)

#save eight bit plane eightbitimg =


np.reshape(eightbitimg,(row,col))
cv2.imwrite("8bitvalue.jpg" , eightbitimg )

#save eight bit plane sevenbitimg =


np.reshape(sevenbitimg,(row,col))
cv2.imwrite("7bitvalue.jpg",sevenbitimg)

#grayscale version of original image gray


=
cv2.imread("WIN_20170511_13_06_18_Pro.jpg",cv2.IMREAD_GRAYSCALE
)
cv2.imwrite("gray.jpeg",gray)

The images are as : eight Bit image:

seventh bit image


PROGRAM-7

AIM- Write a Program to display a Histogram of an image

Importing image data


import matplotlib.pyplot as plt #importing matplotlib
The image should be used in a PNG file as matplotlib supports only PNG
images. Here, It’s a 24-bit RGB PNG image (8 bits for each of R, G, B) used in
this example. Each inner list represents a pixel. Here, with an RGB image,
there are 3 values. For RGB images, matplotlib supports float32 and uint8 data
types.
img = plt.imread('flower.png') #reads image data
In Matplotlib, this is performed using the imshow() function. Here we have
grabbed the plot object.
All about Histogram
Histogram is considered as a graph or plot which is related to frequency of
pixels in an Gray Scale Image with pixel values (ranging from 0 to 255).
Grayscale image is an image in which the value of each pixel is a single
sample, that is, it carries only intensity information where pixel value varies
from 0 to 255. Images of this sort, also known as black-and-white, are
composed exclusively of shades of gray, varying from black at the weakest
intensity to white at the strongest where Pixel can be considered as a every
point in an image. How GrayScale Image looks like:
It quantifies the number of pixels for each intensity value considered. Before going through
Histogram, lets have a rough idea from this given example
we get intuition about contrast, brightness, intensity distribution
etc of that image. As we can see the image and its histogram
which is drawn for grayscale image, not color image. Left
region of histogram shows the amount of darker pixels in image
and right region shows the amount of brighter pixels.
Histogram creation using NumPy array

To create a histogram of our image data, we use the hist() function.


plt.hist(n_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
#calculati ing histogram

In our histogram, it looks like there’s distribution of intensity all over image
Black and White pixels as grayscale image.
From the histogram, we can conclude that dark region is more than brighter
region.
Now, we will deal with an image which consist of intensity distribution of pixels
where pixel value varies. First, we need to calculate histogram using OpenCV
in-built function.
Histogram Calculation
Here, we use cv2.calcHist()(in-built function in OpenCV) to find the histogram.
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[,
accumulate]])

images : it is the source image of type uint8 or float32 represented as “[img]”.


channels : it is the index of channel for which we calculate histogram. For
grayscale image, its value is [0] and
color image, you can pass [0], [1] or [2] to calculate histogram of blue, green
or red channel respectively. mask : mask image. To find histogram of full
image, it is given as “None”. his size : this represents our BIN count. For full
scale, we pass [256]. ranges : this is our RANGE. Normally, it is [0,256].
.
# load an image in grayscale mode
img = cv2.imread('ex.jpg',0)
# calculate frequency of pixels in range 0-255 histg
= cv2.calcHist([img],[0],None,[256],[0,256])

Then, we need to plot histogram to show the characteristics of an image.


Plotting Histograms Analysis
using Matplotlib:

# importing required libraries of opencv import


cv2

# importing library for plotting from


matplotlib import pyplot as plt
# reads an input image img =
cv2.imread('ex.jpg',0)
# find frequency of pixels in range 0-255 histr =
cv2.calcHist([img],[0],None,[256],[0,256])
# show the plotting graph of an image
plt.plot(histr) plt.show()

Input
Output:-
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('ex.jpg',0)
# alternative way to find histogram of an image
plt.hist(img.ravel(),256,[0,256])
plt.show()

PROGRAM-8

AIM: Write a Program to perform Log Transformation of


an image

Log transformation
Logarithmic transformation of an image is one of the gray level
image transformations. Log transformation of an image means
replacing all pixel values, present in the image, with its
logarithmic values. Log transformation is used for image
enhancement as it expands dark pixels of the image as
compared to higher pixel values.
The formula for applying log transformation in an image is,
S = c * log (1 + r)
where,
R = input pixel value,
C = scaling constant and
S = output pixel value
The value of ‘c’ is chosen such that we get the maximum output
value corresponding to the bit size used. So, the formula for
calculating ‘c’ is as follows:
c = 255 / (log (1 + max_input_pixel_value))
When we apply log transformation in an image and any pixel
value is ‘0’ then its log value will become infinite. That’s why we
are adding ‘1’ to each pixel value at the time of log
transformation so that if any pixel value is ‘0’, it will become ‘1’
and its log value will be ‘0’.
Let’s apply log transformation in an image using Python.
Input:-

import cv2 import numpy as np


import matplotlib.pyplot as plt

# Read an image
image = cv2.imread('GFG.png')
# Apply log transformation method c =
255 / np.log(1 + np.max(image))
log_image = c * (np.log(image + 1))
# Specify the data type so that # float value will
be converted to int log_image =
np.array(log_image, dtype = np.uint8)

# Display both images


plt.imshow(image) plt.show()
plt.imshow(log_image)
plt.show()

output:-

Log transformation of gives actual information by enhancing the


image. If we apply this method in an image having higher pixel
values then it will enhance the image more and actual
information of the image will be lost. So, this method can’t be
applied everywhere. It can be applied in images where low pixel
values are more than higher ones.

PROGRAM-9
AIM: Write a Program to implement an Ideal low pass filter

In the field of Image Processing, Ideal Lowpass Filter (ILPF) is used for
image smoothing in the frequency domain. It removes high-frequency noise
from a digital image and preserves low-frequency components.\
Input:-

Output:-
Program -10

AIM:- Write a Program to implement Butterworth low pass filter


MATLAB - Butterworth Lowpass Filter in Image
Processing
In the field of Image Processing, Butterworth Lowpass Filter (BLPF) is used for
image smoothing in the frequency domain. It removes high-frequency noise from a
digital image and preserves low-frequency components. The transfer function of
BLPF of order n is defined as H(u, v) 1 1+[D(u,v)/Do]2" 2n =

Where,

Do is a positive constant. BLPF passes all the frequencies less than Do value without
attenuation and cuts off all the frequencies greater than it.

• This DO is the transition point between Do H(u, v) = 1 and H(u, v) = 0, so this is


termed

as cutoff frequency. But instead of making a sharp cut-off (like, Ideal Lowpass Filter
(ILPF)), it introduces a smooth transition from 1 to 0 to reduce ringing artifacts.

D(u, v) is the Euclidean Distance from any point (u, v) to the origin of the

frequency plane, i.e,

D(u, v)=√(u² + v²)

Approach:

Step 1: Input - Read an image

Step 2: Saving the size of the input image in pixels

Step 3: Get the Fourier Transform of the input image

Step 4: Assign the order n and cut-off frequency Do

Step 5: Designing filter: Butterworth Low Pass Filter


Step 6: Convolution between the Fourier The transformed input image and the
filtering mask

Step 7: Take Inverse Fourier Transform of the convoluted image

Step 8: Display the resultant image as

INPUT:-

OUTPUT:-

You might also like