0% found this document useful (0 votes)
29 views10 pages

Lab Session

The document discusses reading and processing images in Python using OpenCV. It covers installing OpenCV, reading images from files or webcams, displaying images, and performing operations like converting to grayscale. Functions covered include imread(), imshow(), imwrite() and more.

Uploaded by

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

Lab Session

The document discusses reading and processing images in Python using OpenCV. It covers installing OpenCV, reading images from files or webcams, displaying images, and performing operations like converting to grayscale. Functions covered include imread(), imshow(), imwrite() and more.

Uploaded by

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

Computer Vision and Image Processing

Working with Image using Python


Overview of Python
The Python programming language is an increasingly popular choice for both beginners and
experienced developers. Flexible and versatile, Python has strengths in scripting, automation,
data analysis, machine learning, and back-end development.

Installing Python on Windows 10


Step 1 — Downloading the Python Installer
1. Go to the official Python download page for Windows.
2. Find a stable Python 3 release. This tutorial was tested with Python version 3.10.10.
3. Click the appropriate link for your system to download the executable file: Windows
installer (64-bit) or Windows installer (32-bit).
You can download it here: https://www.python.org/

Step 2 — Running the Executable Installer


1. After the installer is downloaded, double-click the .exe file, for example python-3.10.10-
amd64.exe, to run the Python installer.
2. Select the Install launcher for all users checkbox, which enables all users of the computer
to access the Python launcher application.
3. Select the Add python.exe to PATH checkbox, which enables users to launch Python from
the command line.

4. If you’re just getting started with Python and you want to install it with default features as
described in the dialog, then click Install Now and go to Step 4 - Verify the Python
Installation. To install other optional and advanced features, click Customize installation
and continue.
5. The Optional Features include common tools and resources for Python and you can
install all of them, even if you don’t plan to use them.
Step 3 — Verify the Python Installation
You can verify whether the Python installation is successful either through the command line or
through the Integrated Development Environment (IDLE) application, if you chose to install it.
Go to Start and enter cmd in the search bar. Click Command Prompt.
Enter the following command in the command prompt:
python --version
or
py --version

You can also check the version of Python by opening the IDLE application. Go to Start and enter
python in the search bar and then click the IDLE app, for example IDLE (Python 3.10 64-bit).
You can start coding in Python using IDLE or your preferred code editor.
You can also check pip version in cmd by:
python pip --version
or
py -m pip --version

Installing OpenCV on Windows


OPENCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to
perform operations on pictures or videos. It was originally developed by Intel but was later maintained by
Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available in
multiple programming languages such as Python, C++ etc.
OpenCV can be directly downloaded and installed with the use of pip (package manager). To install
OpenCV, just go to the command-line and type the following command:
pip install opencv-python

or
py -m pip install opencv-python
Reading an image in OpenCV using Python
Some basic functions of the OpenCV library
Reading an image
img = cv2.imread('LOCATION OF THE IMAGE')
The above function imread stores the image at the given location to the variable img.
Converting an image to grayscale
img = cv2.imread('watch.jpg',cv2.IMREAD_GRAYSCALE)

The above function converts the image to grayscale and then stores it in the variable img.
Showing the stored image
cv2.imshow('image',img)

The above function shows the image stored in img variable.


Save an image to a file
cv2.imwrite(filename, img)

The above function stores the image in the file. The image is stored in the variable of type Mat that is in
the form of a matrix.
Reading video directly from the webcam
cap = cv2.VideoCapture(0)

Stores live video from your webcam in the variable cap.


Reading a video from local storage
cap = cv2.VideoCapture('LOCATION OF THE VIDEO')

Stores the video located in the given location to the variable.


To check if the video is successfully stored in the variable
cap.isOpened()

cap is the variable that contains the video. The above function returns true if the video is successfully
opened else returns false.
Release the stored video after processing is done
cap.release()

In this section, we’ll try to open an image by using OpenCV (Open Source Computer Vision) library.
Following types of files are supported in OpenCV library:

 Windows bitmaps – *.bmp, *.dib


 JPEG files – *.jpeg, *.jpg
 Portable Network Graphics – *.png
 WebP – *.webp
 Sun rasters – *.sr, *.ras
 TIFF files – *.tiff, *.tif
 Raster and Vector geospatial data supported by GDAL
To use the OpenCV library in python, we need to install these libraries as a prerequisite:
1. Numpy Library: The computer processes images in the form of a matrix for which NumPy is used
and OpenCV uses it in the background.
2. OpenCV python: OpenCV library previously it was cv but the updated version is cv2. It is used to
manipulate images and videos.
The steps to read and display an image in OpenCV are:
1. Read an image using imread() function.
2. Create a GUI window and display image using imshow() function.
3. Use function waitkey(0) to hold the image window on the screen by the specified number of
seconds, o means till the user closes it, it will hold GUI window on the screen.
4. Delete image window from the memory after displaying using destroyAllWindows() function.
Let’s start reading an image. using cv2.
To read the images cv2.imread() method is used. This method loads an image from the specified file. If
the image cannot be read (because of missing file, improper permissions, unsupported or invalid format)
then this method returns an empty matrix.
Syntax: cv2.imread(path, flag)
Parameters:
path: A string representing the path of the image to be read.
flag: It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR
Return Value: This method returns an image that is loaded from the specified file.
Note:
1. The image should be in the working directory or a full path of image should be given.
2. By default, OpenCV stores colored images in BGR(Blue Green and Red) format.
All three types of flags are described below:
cv2.IMREAD_COLOR: It specifies to load a color image. Any transparency of image will be neglected.
It is the default flag. Alternatively, we can pass integer value 1 for this flag.
cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale mode. Alternatively, we can pass
integer value 0 for this flag.
cv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha channel.
Alternatively, we can pass integer value -1 for this flag.

Below codes are implementations to read images and display images on the screen using OpenCV and
matplotlib libraries functions.
Example #1 (Using OpenCV) :
Image used is:

# Python code to read image


import cv2

# To read image from disk, we use


# cv2.imread function, in below method,
img = cv2.imread("strawberries.jpg", cv2.IMREAD_COLOR)

# Creating GUI window to display an image on screen


# first Parameter is windows title (should be in string format)
# Second Parameter is image array
cv2.imshow("image", img)
# To hold the window on screen, we use cv2.waitKey method
# Once it detected the close input, it will release the control
# To the next line
# First Parameter is for holding screen for specified milliseconds
# It should be positive integer. If 0 pass an parameter, then it will
# hold the screen until user close it.
cv2.waitKey(0)

# It is for removing/deleting created GUI window from screen


# and memory
cv2.destroyAllWindows()

Output:

Reading an image using cv2 in BGR format


We can see the shape , i.e., width and height and channels of the image using shape attribute.
img.shape
Output:
(427, 640, 3)
Matplotlib library uses RGB color format to read a colored image. Here we are demonstrating an example
of reading an image using this library.
Example#2

#import cv2, numpy and matplotlib libraries


import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread("strawberries.jpg")
#Displaying image using plt.imshow() method
plt.imshow(img)

#hold the window


plt.waitforbuttonpress()
plt.close('all')

Image read using cv2 and displaying using matplotlib will display picture in BGR format.
Note: See the difference in colors of images read by cv2 and matplotlib library. Because cv2 uses BGR
color format and matplotlib uses RGB color format. To convert BGR to RGB, we us a function:
Example#3:

#import cv2, numpy and matplotlib libraries


import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread("strawberries.jpg")

# Converting BGR color to RGB color format


RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#Displaying image using plt.imshow() method


plt.imshow(RGB_img)

# hold the window


plt.waitforbuttonpress()
plt.close('all')

Output:

BGR color format changes to RGB color format


Example #4: Opening in grayscale mode

# Python program to explain cv2.imread() method

# importing cv2
import cv2

# path
path = r'strawberries.jpg'

# Using cv2.imread() method


# Using 0 to read image in grayscale mode
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
# Displaying the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output :

You might also like