Of course! Here is a comprehensive set of OpenCV Python samples, starting from the absolute basics and progressing to more common and practical tasks.

Prerequisites
First, make sure you have OpenCV and NumPy installed. If not, open your terminal or command prompt and run:
pip install opencv-python pip install numpy pip install matplotlib # Often used for displaying images in notebooks
Sample 1: Reading, Displaying, and Saving an Image
This is the "Hello, World!" of image processing. We'll read an image from a file, show it in a window, and save a modified version.
import cv2
import os
# --- 1. Reading an Image ---
# Make sure you have an image file named 'lena.jpg' in the same directory,
# or provide the full path to an image.
# If you don't have one, you can download one from:
# https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png
image_path = 'lena.jpg'
# Check if the image file exists
if not os.path.exists(image_path):
print(f"Error: Image file not found at '{image_path}'")
# Create a dummy black image for demonstration if the file is missing
print("Creating a dummy black image for demonstration...")
img = np.zeros((512, 512, 3), np.uint8)
cv2.putText(img, "Image Not Found", (100, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
else:
# cv2.IMREAD_COLOR loads the image in BGR format (default)
# cv2.IMREAD_GRAYSCALE loads the image in grayscale
# cv2.IMREAD_UNCHANGED loads the image as-is, including alpha channel
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
# --- 2. Displaying the Image ---
# Create a window to display the image
cv2.imshow('Original Image', img)
# Wait for a key press. The '0' means it will wait indefinitely.
# If you provide a number (e.g., 5000), it will wait for 5000 ms.
print("Press any key to continue...")
cv2.waitKey(0)
# --- 3. Modifying the Image ---
# Let's convert the image to grayscale
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# --- 4. Saving the Image ---
# Save the grayscale image to a new file
output_path = 'lena_gray.jpg'
cv2.imwrite(output_path, gray_image)
print(f"Grayscale image saved to '{output_path}'")
# --- 5. Displaying the Modified Image ---
cv2.imshow('Grayscale Image', gray_image)
print("Press any key to exit...")
cv2.waitKey(0)
# --- 6. Cleaning Up ---
# Close all OpenCV windows
cv2.destroyAllWindows()
Sample 2: Working with Video (From Camera and File)
OpenCV can easily capture and process video streams.
A. Capturing Video from a Webcam
import cv2
# Create a VideoCapture object. 0 is usually the default webcam.
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
print("Error: Could not open video device")
exit()
# Loop to read frames from the webcam
while True:
# cap.read() returns a boolean (success) and the video frame
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Display the resulting frame
cv2.imshow('Webcam Feed', frame)
# The 'q' key is used to quit the loop
# cv2.waitKey(1) waits for 1ms, allowing the window to update
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture and close windows
cap.release()
cv2.destroyAllWindows()
B. Playing a Video File
This is very similar to the webcam example. Just change the source.

import cv2
# Create a VideoCapture object for a video file
# Replace 'my_video.mp4' with the path to your video file
cap = cv2.VideoCapture('my_video.mp4')
if not cap.isOpened():
print("Error: Could not open video file")
exit()
while True:
ret, frame = cap.read()
# If the frame is not read correctly, it means the video has ended
if not ret:
print("Video playback finished.")
break
# You can process the frame here, e.g., convert to grayscale
# gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# cv2.imshow('Video Playback (Grayscale)', gray_frame)
cv2.imshow('Video Playback', frame)
# Exit if 'q' is pressed
if cv2.waitKey(25) & 0xFF == ord('q'): # 25ms delay is good for most videos
break
cap.release()
cv2.destroyAllWindows()
Sample 3: Basic Image Operations
These are fundamental operations you'll use constantly.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load an image
img = cv2.imread('lena.jpg')
if img is None:
print("Image not found. Please run Sample 1 first or provide a valid path.")
exit()
# --- 1. Accessing Pixel Values ---
# Get the pixel value at (100, 100)
pixel_value = img[100, 100]
print(f"Pixel value at (100, 100) in BGR: {pixel_value}")
# Get the Blue, Green, and Red values separately
blue = img[100, 100, 0]
green = img[100, 100, 1]
red = img[100, 100, 2]
print(f"BGR values at (100, 100): B={blue}, G={green}, R={red}")
# --- 2. Modifying Pixel Values ---
# Set a region of interest (ROI) to a specific color
# This will draw a small red square in the top-left corner
img[0:100, 0:100] = [0, 0, 255] # BGR format for Red
# --- 3. Resizing an Image ---
# Resize to 50% of the original size
resized_img = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
# --- 4. Cropping an Image ---
# Crop using array slicing [y_start:y_end, x_start:x_end]
cropped_img = img[100:400, 200:500]
# --- 5. Drawing Shapes and Text ---
drawing_img = img.copy()
# Draw a green diagonal line
cv2.line(drawing_img, (0, 0), (511, 511), (0, 255, 0), 5)
# Draw a blue rectangle
cv2.rectangle(drawing_img, (100, 100), (400, 400), (255, 0, 0), 3)
# Draw a red circle
cv2.circle(drawing_img, (255, 255), 100, (0, 0, 255), -1) # -1 for filled circle
# Add white text
cv2.putText(drawing_img, 'OpenCV', (10, 500), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3)
# --- Displaying all results ---
# Note: cv2.imshow() expects BGR images, matplotlib expects RGB.
# We need to convert for matplotlib.
plt.figure(figsize=(12, 8))
# Original Image
plt.subplot(2, 3, 1)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))"Original")
# Modified Pixel
plt.subplot(2, 3, 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))"Modified Pixel (Red Square)")
# Resized
plt.subplot(2, 3, 3)
plt.imshow(cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB))"Resized")
# Cropped
plt.subplot(2, 3, 4)
plt.imshow(cv2.cvtColor(cropped_img, cv2.COLOR_BGR2RGB))"Cropped")
# Drawing
plt.subplot(2, 3, 5)
plt.imshow(cv2.cvtColor(drawing_img, cv2.COLOR_BGR2RGB))"Drawing Shapes & Text")
plt.show()
Sample 4: Image Processing with Filters
This sample demonstrates common filters like blurring, edge detection, and thresholding.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load a grayscale image for edge detection and thresholding
img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
if img is None:
print("Image not found. Please provide a valid path.")
exit()
# --- 1. Blurring (Smoothing) ---
# Averaging blur
blur_avg = cv2.blur
