Mathew K Analytics

Python library centre

Introduction to OpenCV in Python: Essential Computer Vision Techniques Explained

OpenCV is a powerful open-source library for computer vision. It helps computers to understand images and videos. OpenCV is used for object detection, face…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Introduction to OpenCV#

  • OpenCV is a powerful open-source library for computer vision.
  • It helps computers to understand images and videos.
  • OpenCV is used for object detection, face recognition, image editing, and more.
  • Real world uses include robotics, medical imaging, selfie filters, and video analysis.
  • In this lesson, you will learn key basics and see practical examples with OpenCV.
import warnings; warnings.filterwarnings("ignore")
import cv2
import numpy as np

# If you are on Windows and do not have OpenCV, run:
# pip install opencv-python

Core Concepts in OpenCV#

  • Images in OpenCV are numpy arrays.
  • You can load, display, and save images easily.
  • OpenCV works with color (BGR) and grayscale images.
  • Key functions: cv2.imread(), cv2.imshow(), cv2.imwrite(), cv2.cvtColor()
  • Images can be processed pixel by pixel.
# Let us create an image using numpy
img = np.zeros((100, 100, 3), dtype=np.uint8)
print(type(img))
print(img.shape)
<class 'numpy.ndarray'>
(100, 100, 3)
# Let us save the created image to disk.
cv2.imwrite("black_square.png", img)
print("Image saved as black_square.png")
Image saved as black_square.png

Reading and Displaying Images#

  • You can load images from files using cv2.imread().
  • Displaying images in Jupyter requires matplotlib.
  • Images can be displayed with colors or in grayscale.
import matplotlib.pyplot as plt
img2 = cv2.imread("Mathew.png")
plt.imshow(img2)
plt.title("Loaded Image")
plt.axis("off")
plt.show()
No description has been provided for this image
# Convert image to grayscale
gray_img = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
plt.imshow(gray_img, cmap="gray")
plt.title("Grayscale Image")
plt.axis("off")
plt.show()
No description has been provided for this image

Beginner Example: Drawing a Line#

  • OpenCV lets you draw shapes on images.
  • You can draw lines, rectangles, circles, and add text.
img_line = img2.copy()
cv2.line(img_line, (10, 10), (2500, 2500), (255, 0, 0), 8)
plt.imshow(img_line)
plt.title("Line drawn")
plt.axis("off")
plt.show()
No description has been provided for this image
# Beginner Example: Drawing a rectangle
img_rect = img2.copy()
cv2.rectangle(img_rect, (300, 300), (1900, 1900), (0, 255, 0), 8)
plt.imshow(img_rect)
plt.title("Rectangle drawn")
plt.axis("off")
plt.show()
No description has been provided for this image
# Beginner Example: Adding Text
img_text = img2.copy()
cv2.putText(img_text, "Mathew Analytics", (650, 200), cv2.FONT_HERSHEY_SIMPLEX, 4, (255,255,255), 20)
plt.imshow(img_text)
plt.title("Text added")
plt.axis("off")
plt.show()
No description has been provided for this image

Intermediate Example: Image Thresholding#

  • Thresholding converts grayscale images to black and white.
  • It is used to separate objects from background.
_, thresh_img = cv2.threshold(gray_img, 50, 255, cv2.THRESH_BINARY)
plt.imshow(thresh_img, cmap="gray")
plt.title("Thresholded Image")
plt.axis("off")
plt.show()
No description has been provided for this image
# Intermediate Example: Blurring an Image
blur_img = cv2.GaussianBlur(img2, (7,7), 0)
plt.imshow(blur_img)
plt.title("Blurred Image")
plt.axis("off")
plt.show()
No description has been provided for this image
# Intermediate Example: Flipping an Image
flip_img = cv2.flip(img2, 1)
plt.imshow(flip_img)
plt.title("Image Flipped Horizontally")
plt.axis("off")
plt.show()
No description has been provided for this image

Advanced Example: Edge Detection#

  • Edge detection highlights borders in images.
  • OpenCV makes it easy with the Canny function.
edges = cv2.Canny(gray_img, 30, 100)
plt.imshow(edges, cmap="gray")
plt.title("Edges Detected")
plt.axis("off")
plt.show()
No description has been provided for this image
# Advanced Example: Contour Detection
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
img_contour = img2.copy()
cv2.drawContours(img_contour, contours, -1, (0,255,255), 2)
plt.imshow(img_contour)
plt.title("Contours Detected")
plt.axis("off")
plt.show()
No description has been provided for this image

Error Handling in OpenCV#

  • Sometimes images may not be found or functions may fail.
  • Use try-except to catch errors and show messages.
try:
    missing_img = cv2.imread("non_existent_file.jpg")
    if missing_img is None:
        raise FileNotFoundError("Image file not found.")
    plt.imshow(missing_img)
except FileNotFoundError as e:
    print(e)
Image file not found.
# Debugging: Checking Image Properties
def check_image(img):
    if img is None:
        print("Image is None. Check file path or data.")
        return
    print("Image shape:", img.shape)
    print("Image data type:", img.dtype)

check_image(img2)
Image shape: (2208, 2208, 3)
Image data type: uint8

Best Practices with OpenCV#

  • Always check if images are loaded correctly.
  • Work with image copies to avoid losing original data.
  • Use clear variable names for readability.
  • Comment your code to explain steps.
  • Use cv2 functions for common tasks.
# Always check if the image is loaded, and use meaningful variables.
path = 'Mathew.png'
img_loaded = cv2.imread(path)
if img_loaded is not None:
    print(f'Loaded {path} successfully.')
else:
    print(f'Could not load {path}.')
Loaded Mathew.png successfully.

Mini-project: Make a Simple Stamped Badge#

  • Combine your skills to create an image with shapes and text.
  • You will draw a circle, rectangle, and add text to make a badge.
  • Save your badge image to disk.
badge = np.zeros((120, 120, 3), dtype=np.uint8)
cv2.circle(badge, (60, 60), 50, (200, 200, 0), -1)
cv2.rectangle(badge, (20, 90), (100,110), (255,0,0), -1)
cv2.putText(badge, "SUCCESS", (15, 105), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
plt.imshow(badge)
plt.title("Your Badge")
plt.axis("off")
plt.show()
cv2.imwrite("my_badge.png", badge)
No description has been provided for this image
True

Keep Exploring OpenCV!#

  • There is a lot more you can do with images and videos.
  • Try loading your own photos and experimenting.
  • Check out the OpenCV documentation for more.

Thank you for learning OpenCV!#

  • Please like and subscribe to our YouTube channel.
  • Let us know in the comments what you want to learn next.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.