0% found this document useful (0 votes)
23 views28 pages

Getting Started With Python OpenCV - GeeksforGeeks

The document provides a comprehensive guide to getting started with Python OpenCV, including installation instructions and various code examples for image manipulation. Key functionalities covered include reading, displaying, saving, rotating, resizing, color conversion, and performing arithmetic operations on images. The document serves as a practical introduction for beginners to understand and utilize OpenCV in Python.

Uploaded by

onukwuchika684
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)
23 views28 pages

Getting Started With Python OpenCV - GeeksforGeeks

The document provides a comprehensive guide to getting started with Python OpenCV, including installation instructions and various code examples for image manipulation. Key functionalities covered include reading, displaying, saving, rotating, resizing, color conversion, and performing arithmetic operations on images. The document serves as a practical introduction for beginners to understand and utilize OpenCV in Python.

Uploaded by

onukwuchika684
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

Getting Started with Python OpenCV - GeeksforGeeks [Link]

org/python/getting-started-with-python-opencv/

pip3 install opencv-python

1 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python code to read image


import cv2

# To read image from disk, we use


# [Link] function, in below method,
img = [Link]("[Link]", cv2.IMREAD_COLOR)

print(img)

[[[ 87 157 14]


[ 87 157 14]
[ 87 157 14]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]

[[ 87 157 14]
[ 87 157 14]
[ 87 157 14]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]

[[ 87 157 14]
[ 87 157 14]
[ 87 157 14]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]

...

[[ 72 133 9]
[ 72 133 9]
[ 72 133 9]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]

[[ 72 133 9]

2 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

[ 72 133 9]
[ 72 133 9]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]

[[ 72 133 9]
[ 72 133 9]
[ 72 133 9]
...
[ 87 157 14]
[ 87 157 14]
[ 87 157 14]]]

# Python code to read image


import cv2

# To read image from disk, we use


# [Link] function, in below method,
img = [Link]("[Link]", 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
[Link]("GeeksforGeeks", img)

# To hold the window on screen, we use [Link] 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.
[Link](0)

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


# and memory
[Link]()

3 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to explain [Link]() method

# importing cv2
import cv2

image_path = '[Link]'

# Using [Link]() method


# to read the image
img = [Link](image_path)

# Filename
filename = '[Link]'

# Using [Link]() method


# Saving the image
[Link](filename, img)

# Reading and showing the saved image


img = [Link](filename)
[Link]("GeeksforGeeks", img)

[Link](0)
[Link]()

4 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to explain [Link]() method

# importing cv2
import cv2

# path
path = '[Link]'

# Reading an image in default mode


src = [Link](path)

# Window name in which image is displayed


window_name = 'Image'

# Using [Link]() method


# Using cv2.ROTATE_90_CLOCKWISE rotate
# by 90 degrees clockwise
image = [Link](src, cv2.cv2.ROTATE_90_CLOCKWISE)

# Displaying the image


[Link](window_name, image)
[Link](0)

import cv2
import numpy as np

FILE_NAME = '[Link]'

# Read image from the disk.


img = [Link](FILE_NAME)

# Shape of image in terms of pixels.


(rows, cols) = [Link][:2]

# getRotationMatrix2D creates a matrix needed


# for transformation. We want matrix for rotation
# w.r.t center to 45 degree without scaling.
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1)
res = [Link](img, M, (cols, rows))

5 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

[Link]("GeeksforGeeks", res)

[Link](0)
[Link]()



import cv2
import numpy as np
import [Link] as plt

image = [Link]("[Link]", 1)
# Loading the image

half = [Link](image, (0, 0), fx = 0.1, fy = 0.1)


bigger = [Link](image, (1050, 1610))

stretch_near = [Link](image, (780, 540),


interpolation = cv2.INTER_NEAREST)

Titles =["Original", "Half", "Bigger", "Interpolation Nearest"]


images =[image, half, bigger, stretch_near]
count = 4

for i in range(count):
[Link](2, 3, i + 1)
[Link](Titles[i])
[Link](images[i])

6 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

[Link]()

# Python program to explain [Link]() method

# importing cv2
import cv2

# path
path = '[Link]'

# Reading an image in default mode


src = [Link](path)

# Window name in which image is displayed


window_name = 'GeeksforGeeks'

# Using [Link]() method


# Using cv2.COLOR_BGR2GRAY color space
# conversion code
image = [Link](src, cv2.COLOR_BGR2GRAY )

# Displaying the image


[Link](window_name, image)

[Link](0)
[Link]()

7 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# arithmetic operation of
# addition of two images

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command

8 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

image1 = [Link]('[Link]')
image2 = [Link]('[Link]')

# [Link] is applied over the


# image inputs with applied parameters
weightedSum = [Link](image1, 0.5, image2, 0.4, 0)

# the window showing output image


# with the weighted sum
[Link]('Weighted Image', weightedSum)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

# Python program to illustrate


# arithmetic operation of
# subtraction of pixels of two images

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command
image1 = [Link]('[Link]')
image2 = [Link]('[Link]')

# [Link] is applied over the


# image inputs with applied parameters
sub = [Link](image1, image2)

# the window showing output image


# with the subtracted image
[Link]('Subtracted Image', sub)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

9 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]




# Python program to illustrate


# arithmetic operation of
# bitwise AND of two images

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command
img1 = [Link]('[Link]')

10 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

img2 = [Link]('[Link]')

# cv2.bitwise_and is applied over the


# image inputs with applied parameters
dest_and = cv2.bitwise_and(img2, img1, mask = None)

# the window showing output image


# with the Bitwise AND operation
# on the input images
[Link]('Bitwise And', dest_and)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

# Python program to illustrate


# arithmetic operation of
# bitwise OR of two images

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command
img1 = [Link]('[Link]')
img2 = [Link]('[Link]')

# cv2.bitwise_or is applied over the


# image inputs with applied parameters
dest_or = cv2.bitwise_or(img2, img1, mask = None)

# the window showing output image


# with the Bitwise OR operation
# on the input images
[Link]('Bitwise OR', dest_or)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

11 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# arithmetic operation of
# bitwise XOR of two images

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command
img1 = [Link]('[Link]')
img2 = [Link]('[Link]')

# cv2.bitwise_xor is applied over the


# image inputs with applied parameters
dest_xor = cv2.bitwise_xor(img1, img2, mask = None)

# the window showing output image


# with the Bitwise XOR operation
# on the input images
[Link]('Bitwise XOR', dest_xor)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

12 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# arithmetic operation of
# bitwise NOT on input image

# organizing imports
import cv2
import numpy as np

# path to input images are specified and


# images are loaded with imread command
img1 = [Link]('[Link]')
img2 = [Link]('[Link]')

# cv2.bitwise_not is applied over the


# image input with applied parameters
dest_not1 = cv2.bitwise_not(img1, mask = None)
dest_not2 = cv2.bitwise_not(img2, mask = None)

# the windows showing output image


# with the Bitwise NOT operation
# on the 1st and 2nd input image
[Link]('Bitwise NOT on image 1', dest_not1)
[Link]('Bitwise NOT on image 2', dest_not2)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

13 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

import cv2
import numpy as np

image = [Link]('[Link]')

# Store height and width of the image


height, width = [Link][:2]

quarter_height, quarter_width = height / 4, width / 4

T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]])

# We use warpAffine to transform


# the image using the matrix, T
img_translation = [Link](image, T, (width, height))

[Link]('Translation', img_translation)
[Link](0)

[Link]()

import cv2

FILE_NAME = '[Link]'

# Read image from disk.


img = [Link](FILE_NAME)

# Canny edge detection.

14 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

edges = [Link](img, 100, 200)

# Write image back to disk.


[Link]('Edges', edges)
[Link](0)
[Link]()

If f (x, y) < T
then f (x, y) = 0
else
f (x, y) = 255

where
f (x, y) = Coordinate Pixel Value
T = Threshold Value.


15 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# simple thresholding type on an image

# organizing imports
import cv2
import numpy as np

# path to input image is specified and


# image is loaded with imread command
image1 = [Link]('[Link]')

# [Link] is applied over the


# image input with applied parameters
# to convert the image in grayscale
img = [Link](image1, cv2.COLOR_BGR2GRAY)

# applying different thresholding


# techniques on the input image
# all pixels value above 120 will
# be set to 255
ret, thresh1 = [Link](img, 120, 255, cv2.THRESH_BINARY)
ret, thresh2 = [Link](img, 120, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = [Link](img, 120, 255, cv2.THRESH_TRUNC)
ret, thresh4 = [Link](img, 120, 255, cv2.THRESH_TOZERO)
ret, thresh5 = [Link](img, 120, 255, cv2.THRESH_TOZERO_INV)

# the window showing output images


# with the corresponding thresholding
# techniques applied to the input images
[Link]('Binary Threshold', thresh1)
[Link]('Binary Threshold Inverted', thresh2)
[Link]('Truncated Threshold', thresh3)
[Link]('Set to 0', thresh4)
[Link]('Set to 0 Inverted', thresh5)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

16 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# adaptive thresholding type on an image

# organizing imports
import cv2
import numpy as np

# path to input image is specified and


# image is loaded with imread command
image1 = [Link]('[Link]')

# [Link] is applied over the


# image input with applied parameters
# to convert the image in grayscale
img = [Link](image1, cv2.COLOR_BGR2GRAY)

# applying different thresholding


# techniques on the input image
thresh1 = [Link](img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 199, 5)

thresh2 = [Link](img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,


cv2.THRESH_BINARY, 199, 5)

# the window showing output images


# with the corresponding thresholding
# techniques applied to the input image
[Link]('Adaptive Mean', thresh1)
[Link]('Adaptive Gaussian', thresh2)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

17 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python program to illustrate


# Otsu thresholding type on an image

# organizing imports
import cv2
import numpy as np

# path to input image is specified and


# image is loaded with imread command
image1 = [Link]('[Link]')

# [Link] is applied over the


# image input with applied parameters
# to convert the image in grayscale
img = [Link](image1, cv2.COLOR_BGR2GRAY)

# applying Otsu thresholding


# as an extra flag in binary
# thresholding
ret, thresh1 = [Link](img, 120, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)

# the window showing output image


# with the corresponding thresholding
# techniques applied to the input image
[Link]('Otsu Threshold', thresh1)

# De-allocate any associated memory usage


if [Link](0) & 0xff == 27:
[Link]()

18 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# importing libraries
import cv2
import numpy as np

image = [Link]('[Link]')

[Link]('Original Image', image)


[Link](0)

# Gaussian Blur
Gaussian = [Link](image, (7, 7), 0)
[Link]('Gaussian Blurring', Gaussian)
[Link](0)

# Median Blur
median = [Link](image, 5)
[Link]('Median Blurring', median)
[Link](0)

# Bilateral Blur
bilateral = [Link](image, 9, 75, 75)
[Link]('Bilateral Blurring', bilateral)
[Link](0)
[Link]()

19 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]


import cv2

# Read the image


img = [Link]('[Link]')

# Apply bilateral filter with d = 30,


# sigmaColor = sigmaSpace = 100
bilateral = [Link](img, 15, 100, 100)

# Save the output


[Link]('Bilateral', bilateral)
[Link](0)
[Link]()

20 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

import cv2
import numpy as np

# Let's load a simple image with 3 black squares


image = [Link]('[Link]')
[Link](0)

# Grayscale
gray = [Link](image, cv2.COLOR_BGR2GRAY)

# Find Canny edges


edged = [Link](gray, 30, 200)
[Link](0)

# Finding Contours
# Use a copy of the image e.g. [Link]()
# since findContours alters the image
contours, hierarchy = [Link](edged,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

[Link]('Canny Edges After Contouring', edged)


[Link](0)

print("Number of Contours found = " + str(len(contours)))

# Draw all contours


# -1 signifies drawing all contours
[Link](image, contours, -1, (0, 255, 0), 3)

[Link]('Contours', image)
[Link](0)
[Link]()

21 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]







# Python program to demonstrate erosion and


# dilation of images.
import cv2
import numpy as np

# Reading the input image


img = [Link]('[Link]', 0)

# Taking a matrix of size 5 as the kernel


kernel = [Link]((5,5), np.uint8)

# The first parameter is the original image,


# kernel is the matrix with which image is
# convolved and third parameter is the number
# of iterations, which will determine how much
# you want to erode/dilate a given image.
img_erosion = [Link](img, kernel, iterations=1)
img_dilation = [Link](img, kernel, iterations=1)

[Link]('Input', img)
[Link]('Erosion', img_erosion)
[Link]('Dilation', img_dilation)

[Link](0)
[Link]()

22 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

import numpy as np
import cv2

# Read the query image as query_img


# and train image This query image
# is what you need to find in train image
# Save it in the same directory
# with the name [Link]
query_img = [Link]('[Link]')
train_img = [Link]('[Link]')

# Convert it to grayscale
query_img_bw = [Link](query_img,cv2.COLOR_BGR2GRAY)
train_img_bw = [Link](train_img, cv2.COLOR_BGR2GRAY)

# Initialize the ORB detector algorithm


orb = cv2.ORB_create()

# Now detect the keypoints and compute


# the descriptors for the query image
# and train image
queryKeypoints, queryDescriptors = [Link](query_img_bw,None)

23 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

trainKeypoints, trainDescriptors = [Link](train_img_bw,None)

# Initialize the Matcher for matching


# the keypoints and then match the
# keypoints
matcher = [Link]()
matches = [Link](queryDescriptors,trainDescriptors)

# draw the matches to the final image


# containing both the images the drawMatches()
# function takes both images and keypoints
# and outputs the matched query image with
# its train image
final_img = [Link](query_img, queryKeypoints,
train_img, trainKeypoints, matches[:20],None)

final_img = [Link](final_img, (1000,650))

# Show the final image


[Link]("Matches", final_img)
[Link](0)
[Link]()




24 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# Python3 program to draw rectangle


# shape on solid image
import numpy as np
import cv2

# Creating a black image with 3


# channels RGB and unsigned int datatype
img = [Link]((400, 400, 3), dtype = "uint8")

# Creating rectangle
[Link](img, (30, 30), (300, 200), (0, 255, 0), 5)

[Link]('dark', img)

# Allows us to see image


# until closed forcefully
[Link](0)
[Link]()



25 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

# OpenCV program to detect face in real time


# import libraries of python OpenCV
# where its functionality resides
import cv2

# Trained XML classifiers describes some features of some


# object we want to detect a cascade function is trained
# from a lot of positive(faces) and negative(non-faces)
# images.
face_cascade = [Link]('haarcascade_frontalface_default.xml')

# Trained XML file for detecting eyes


eye_cascade = [Link]('haarcascade_eye.xml')

# capture frames from a camera


cap = [Link](0)

# loop runs if capturing has been initialized.


while 1:

# reads frames from a camera


ret, img = [Link]()

# convert to gray scale of each frames


gray = [Link](img, cv2.COLOR_BGR2GRAY)

# Detects faces of different sizes in the input image


faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:


# To draw a rectangle in a face
[Link](img,(x,y),(x+w,y+h),(255,255,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]

# Detects eyes of different sizes in the input image


eyes = eye_cascade.detectMultiScale(roi_gray)

# To draw a rectangle in eyes


for (ex,ey,ew,eh) in eyes:
[Link](roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)

# Display an image in a window


[Link]('img',img)

# Wait for Esc key to stop


k = [Link](30) & 0xff
if k == 27:
break

# Close the window


[Link]()

# De-allocate any associated memory usage


[Link]()

26 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

27 of 28 2/5/2026, 1:19 PM
Getting Started with Python OpenCV - GeeksforGeeks [Link]

28 of 28 2/5/2026, 1:19 PM

You might also like