18DIP Lab 2
18DIP Lab 2
“Write Program to Read and Display Digital Image using Open CV”
Objective:
• Installation of Anaconda and Running First Program
• Become familiar with Basic commands of Open CV
• Read and display image in Open CV
• Resize given image
• Convert given color image into gray -scale image
• Convert given color/gray -scale image into black & white image
• Draw image profile.
• Separate color image in three R G & B planes
• Create color image using R, G and B three separate planes
• Flow control and LOOP in open CV
• Write given 2 -D data in image file
Apparatus:
• PC/Laptop with Windows 7/8/8.1/10
• Anaconda softwareLatest Anaconda 3 Release - Anaconda 3.7
Theory:
Computer Vision:
Computer Vision can be defined as a discipline that explains how to reconstruct,
interrupt, and understand a 3D scene from its 2D images, in terms of the properties of the
structure present in the scene. It deals with modeling and replicating human vision using
computer software and hardware. Its fields are:
• Image Processing:
It focuses on image manipulation.
• Pattern Recognition:
It explains various techniques to classify patterns.
• Photogrammetry:
It is concerned with obtaining accurate measurements from images.
import cv2
print("Package Imported")
Output:
STEP # 02:
Read Image from the user and Display
Input Code:
img = cv2.imread(r"D:\,\university\8th
s Semester\DIP\lab\lion.PNG")
cv2.imshow("Output", img)
cv2.waitKey(0)
Output:
Output:
Resizing an image means changing the dimensions of it, be it width alone, height alone or
changing both of them. Also, the aspect ratio of the original image could be preserved in the
resized image.
• Img.shape() function returns a tuple of the number of rows, columns, and channels.
• cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])is the function
for resizing.
Where:
Input Code:
Output:
Resized Image
cv2.cvtColor() method is used to convert an image from one color space to another.
There are more than 150 color-space conversion methods available in OpenCV.
Input Code:
Output:
IV. Convert given color/gray -scale image into black & white
image: STEP # 01:
Convert to another color space
Explanation:
• cv2.cvtColor() method is used to convert an image from one color space to another.
There are more than 150 color-space conversion methods available in OpenCV.
• The function cv.threshold is used to apply the thresholding. The first argument is the
source image, which should be a grayscale image. The second argument is the threshold
value which is used to classify the pixel values. The third argument is the maximum
value which is assigned to pixel values exceeding the threshold. OpenCV provides
different types of thresholding which is given by the fourth parameter of the function.
Input Code:
I
Output:
The Import pyplot from matplotlib. It is a collection of command style functions that make
matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g.,
creates a figure, creates a plotting area in a figure, plots some lines in a p otting area. The
function img.ravel function is used to create a contiguous flattened array. A 1-D array,
containing the elements of the input, is returned.
Input Code:
Output:
Output:
CV: Explanation:
Dense Optical flow computes the optical flow vector for every pixel of the frame which may
be responsible for its slow speed but leading to a better accurate result. It can be used for
detecting motion in the videos, video segmentation, learning structure from motion.
Input Code:
import cv2 as cv
import numpy as np
cap = cv.VideoCapture(r"D:\,\Abdul Ahad\MB DATA\memories 4th sem\2.mp4")
# ret = a boolean return value from
# getting the frame, first_frame = the
# first frame in the entire video sequence
ret, first_frame = cap.read()
# Converts frame to grayscale because we only need the luminance channel for
# detecting edges - less computationally expensive
prev_gray = cv.cvtColor(first_frame, cv.COLOR_BGR2GRAY)
# Creates an image filled with zero
# intensities with the same dimensions as the frame
mask = np.zeros_like(first_frame)
# Sets image saturation to maximum
mask[..., 1] = 255
while (cap.isOpened()):
# ret = a boolean return value from getting the frame,
# frame = the current frame being projected in the video
ret, frame = cap.read()
# Opens a new window and displays the input frame
cv.imshow("input", frame)
# Converts each frame to grayscale
# We previously only converted the first frame to grayscale
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Calculates dense optical flow by Farneback method
flow = cv.calcOpticalFlowFarneback(prev_gray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
# Computes the magnitude and angle of the 2D vectors
magnitude, angle = cv.cartToPolar(flow[..., 0], flow[..., 1])
# Sets image hue according to the optical flow direction
mask[..., 0] = angle * 180 / np.pi / 2
# Sets image value according to the optical flow magnitude (normalized)
mask[..., 2] = cv.normalize(magnitude, None, 0, 255, cv.NORM_MINMAX)
# Converts HSV to RGB (BGR) color representation
rgb = cv.cvtColor(mask, cv.COLOR_HSV2BGR)
# Opens a new window and displays the output frame
cv.imshow("dense optical flow", rgb)
# Updates the previous frame
prev_gray = gray
# Frames are read by intervals of 1 millisecond.
# The program breaks out of the loop when the user presses the 'q' key
if cv.waitKey(1) & 0xFF == ord('q'):
break
# The following frees up resources and closes all windows
cap.release()
cv.destroyAllWindows()
OutPut:
Output:
Q1: Write a python program to Opening an image in grayscale mode
Digital Representation: First, an image captured by a camera or scanner is converted into a digital
format.
Image Processing: Once an image is in digital form, various image processing techniques can be
applied
Feature Extraction: For a computer to recognize or understand an image, it must identify
distinguishing features or patterns.
OpenCV is the huge open-source library for the computer vision, machine learning, and
image processing and now it plays a major role in real-time operation which is very important in
today’s systems. By using it, one can process images and videos to identify objects, faces, or even
handwriting of a human. When it integrated with various libraries, such as NumPy, python is
capable of processing the OpenCV array structure for analysis.
Conclusion: