Implemented OpenCV Projects
Repo for all the projects ( vertical post)…

Welcome back peeps.
Since we are now focusing on our goals for 2023 — new vertical series than horizontal ( means you will find all the contents of the series in one post and projects in second than developing/extending it to new posts every time). So, keep checking this post every day to see new projects.
Prerequisite to these projects —
Complete 60 days of Data Science and Machine Learning before starting this series ( link below) —
Projects Videos —
All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).
Subscribe today!
Tech Newsletter —
If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 35K readers. You can subscribe to Ignito:
Let’s dive in!
OpenCV (Open Source Computer Vision Library) is a library of programming functions primarily aimed at real-time computer vision. It is open-source software and it has C++, Python and Java interfaces.
OpenCV contains a wide variety of image processing and computer vision algorithms, including feature detection and description, image segmentation, object detection and recognition, motion analysis, and image and video manipulation.
Some of the key features of OpenCV include:
- Image processing and manipulation: OpenCV provides a wide range of image processing and manipulation functions, including filtering, color space conversions, histogram equalization, and more.
import cv2
import numpy as np
# Load the image
image = cv2.imread('image.jpg')
# Display the original image
cv2.imshow('Original Image', image)
cv2.waitKey(0)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Display the grayscale image
cv2.imshow('Grayscale Image', gray)
cv2.waitKey(0)
# Apply a blur to the image
blur = cv2.GaussianBlur(image, (5, 5), 0)
# Display the blurred image
cv2.imshow('Blurred Image', blur)
cv2.waitKey(0)
# Draw a rectangle on the image
start_point = (100, 100)
end_point = (400, 400)
color = (0, 255, 0) # Green color in BGR
thickness = 3
rectangle = cv2.rectangle(image, start_point, end_point, color, thickness)
# Display the image with the rectangle
cv2.imshow('Image with Rectangle', rectangle)
cv2.waitKey(0)
# Resize the image
resized = cv2.resize(image, (500, 500))
# Display the resized image
cv2.imshow('Resized Image', resized)
cv2.waitKey(0)
# Rotate the image
rows, cols, _ = image.shape
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1)
rotated = cv2.warpAffine(image, M, (cols, rows))
# Display the rotated image
cv2.imshow('Rotated Image', rotated)
cv2.waitKey(0)
# Save the modified image
cv2.imwrite('modified_image.jpg', rotated)
# Close all windows
cv2.destroyAllWindows()- Object detection and recognition: OpenCV includes a variety of object detection and recognition algorithms, including Haar cascades, HOG, and SVM.
import cv2
# Load the Haar cascade XML file for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Load the image
image = cv2.imread('image.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Perform face detection
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 3)
# Display the image with the detected faces
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()- Camera calibration and 3D reconstruction: OpenCV includes functions for camera calibration and 3D reconstruction, allowing for the extraction of 3D information from 2D images.
import cv2
import numpy as np
# Define the number of chessboard corners (inner corners)
num_corners_x = 9
num_corners_y = 6
# Create arrays to store object points and image points from all calibration images
obj_points = [] # 3D points in real world space
img_points = [] # 2D points in image plane
# Generate object points for the chessboard (0,0,0), (1,0,0), (2,0,0) ...., (8,5,0)
objp = np.zeros((num_corners_x * num_corners_y, 3), np.float32)
objp[:, :2] = np.mgrid[0:num_corners_x, 0:num_corners_y].T.reshape(-1, 2)
# Iterate through calibration images
for i in range(1, 11): # Assuming you have 10 calibration images named as 'calibration1.jpg', 'calibration2.jpg', ...
# Load the calibration image
img = cv2.imread(f'calibration{i}.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (num_corners_x, num_corners_y), None)
# If corners are found, add object points and image points
if ret:
obj_points.append(objp)
img_points.append(corners)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (num_corners_x, num_corners_y), corners, ret)
cv2.imshow(f'Chessboard Corners - Image {i}', img)
cv2.waitKey(500) # Delay to display the image
# Perform camera calibration
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None)
# Print the camera matrix and distortion coefficients
print("Camera Matrix:")
print(mtx)
print("\nDistortion Coefficients:")
print(dist)
# Select an image for 3D reconstruction
img_index = 1
img = cv2.imread(f'calibration{img_index}.jpg')
h, w = img.shape[:2]
# Perform undistortion
new_camera_mtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
undistorted_img = cv2.undistort(img, mtx, dist, None, new_camera_mtx)
# Crop the undistorted image
x, y, w, h = roi
undistorted_img = undistorted_img[y:y+h, x:x+w]
# Display the original and undistorted images
cv2.imshow('Original Image', img)
cv2.imshow('Undistorted Image', undistorted_img)
cv2.waitKey(0)
# Perform 3D reconstruction
# Define the 3D object points for the selected image
obj_points_reconstruct = objp
# Project the object points onto the image plane
_, rvecs, tvecs, inliers = cv2.solvePnPRansac(obj_points_reconstruct, img_points[img_index - 1], mtx, dist)
img_points_reconstruct, _ = cv2.projectPoints(obj_points_reconstruct, rvecs, tvecs, mtx, dist)
# Draw the 3D coordinate axes on the image
axis_length = 3 # Length of the coordinate axes in the visualization
# Define the 3D points for the coordinate axes
axis_points = np.float32([[0,0,0], [axis_length,0,0], [0,axis_length,0], [0,0,-axis_length]]).reshape(-1,3)
# Project the coordinate axis points onto the image plane
img_points_axis, _ = cv2.projectPoints(axis_points, rvecs, tvecs, mtx, dist)
# Extract the origin point and the projected points of the axes
origin = tuple(img_points_reconstruct[0].ravel())
x_axis = tuple(img_points_axis[1].ravel())
y_axis = tuple(img_points_axis[2].ravel())
z_axis = tuple(img_points_axis[3].ravel())
# Draw the coordinate axes on the image
img_with_axes = cv2.line(undistorted_img, origin, x_axis, (255, 0, 0), 2) # X-axis (Blue)
img_with_axes = cv2.line(img_with_axes, origin, y_axis, (0, 255, 0), 2) # Y-axis (Green)
img_with_axes = cv2.line(img_with_axes, origin, z_axis, (0, 0, 255), 2) # Z-axis (Red)
# Display the image with the coordinate axes
cv2.imshow('3D Reconstruction with Coordinate Axes', img_with_axes)
cv2.waitKey(0)
cv2.destroyAllWindows()- Video analysis: OpenCV provides functions for analyzing and manipulating video, including optical flow, background subtraction, and more.
import cv2
# Load the video file
video = cv2.VideoCapture('video.mp4')
# Check if the video file was successfully opened
if not video.isOpened():
print("Error opening video file.")
# Read the video frame by frame
while video.isOpened():
# Read a frame from the video
ret, frame = video.read()
# If the frame was successfully read
if ret:
# Perform video analysis operations here
# For example, you can apply image processing, object detection, or any other analysis techniques
# Display the frame
cv2.imshow('Video', frame)
# Press 'q' to exit the video
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
# Break the loop if the video has ended
break
# Release the video capture object and close all windows
video.release()
cv2.destroyAllWindows()OpenCV is widely used for various computer vision and image processing tasks, it is fast and efficient, it can be used on a wide range of platforms, including mobile and embedded devices, and it is easy to integrate into existing software and systems.
This post will house all the OpenCV projects related to the topics below-
Computer Vision and Image Processing
First we will cover above mentioned points in detail and will implement projects —
Learn the Basics of Computer Vision and Image Processing
Computer Vision is a field of study that focuses on enabling computers to interpret and understand visual information from images or videos. It involves the development of algorithms and techniques to extract meaningful information and perform tasks such as object detection, image classification, face recognition, and more.
One of the popular libraries used for Computer Vision tasks in Python is OpenCV (Open Source Computer Vision Library). OpenCV provides a wide range of functions and tools to process images and videos efficiently. Here are some important functions in Computer Vision using OpenCV with Python code:
Image Loading and Display:
import cv2# Load an image
image = cv2.imread('image.jpg')# Display the image
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Resizing:
import cv2# Load an image
image = cv2.imread('image.jpg')# Resize the image to a specific width and height
resized_image = cv2.resize(image, (500, 300))# Display the resized image
cv2.imshow('Resized Image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()Object Detection using Haar Cascades:
import cv2# Load the Haar cascade file for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')# Load an image
image = cv2.imread('image.jpg')# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Perform face detection
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)# Display the image with detected faces
cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Classification using Pretrained Models:
import cv2
import numpy as np
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
from tensorflow.keras.applications.resnet50 import ResNet50# Load a pretrained ResNet50 model
model = ResNet50(weights='imagenet')# Load and preprocess an image
image = cv2.imread('image.jpg')
preprocessed_image = preprocess_input(image)# Expand dimensions to match model input shape
input_image = np.expand_dims(preprocessed_image, axis=0)# Perform image classification
predictions = model.predict(input_image)
decoded_predictions = decode_predictions(predictions, top=5)[0]# Display the top 5 predicted labels and probabilities
for label, _, probability in decoded_predictions:
print(f'{label}: {probability}')Image processing —
Image processing is a subset of Computer Vision that focuses on manipulating and enhancing digital images to improve their quality or extract useful information. It involves applying various techniques and algorithms to modify images, perform feature extraction, noise reduction, image restoration, and more.
Image Grayscale Conversion:
import cv2# Load an image
image = cv2.imread('image.jpg')# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Display the grayscale image
cv2.imshow('Grayscale Image', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Blurring (Smoothing):
import cv2# Load an image
image = cv2.imread('image.jpg')# Apply Gaussian blur to the image
blurred_image = cv2.GaussianBlur(image, (5, 5), 0)# Display the blurred image
cv2.imshow('Blurred Image', blurred_image)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Thresholding:
import cv2# Load a grayscale image
image = cv2.imread('image.jpg', 0)# Apply binary thresholding to the image
_, thresholded_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)# Display the thresholded image
cv2.imshow('Thresholded Image', thresholded_image)
cv2.waitKey(0)
cv2.destroyAllWindows()Edge Detection using Canny Edge Detector:
import cv2# Load an image
image = cv2.imread('image.jpg')# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Apply Canny edge detection to the grayscale image
edges = cv2.Canny(gray_image, threshold1=100, threshold2=200)# Display the edges
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Morphological Operations (Erosion and Dilation):
import cv2
import numpy as np# Load a binary image
image = cv2.imread('binary_image.jpg', 0)# Create a structuring element
kernel = np.ones((5, 5), np.uint8)# Apply erosion and dilation operations
eroded_image = cv2.erode(image, kernel, iterations=1)
dilated_image = cv2.dilate(image, kernel, iterations=1)# Display the eroded and dilated images
cv2.imshow('Eroded Image', eroded_image)
cv2.imshow('Dilated Image', dilated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()OpenCV4 in Python
OpenCV (Open Source Computer Vision) is an open-source computer vision and machine learning library. OpenCV provides a wide range of functions and tools for image and video processing, object detection and tracking, feature extraction, and more. OpenCV4 refers to the fourth major version of OpenCV.
Image Loading and Display: OpenCV provides functions to load and display images.
import cv2
# Load an image
image = cv2.imread('image.jpg')
# Display the image
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()Image Processing: OpenCV offers various image processing functions such as resizing, converting color spaces, blurring, and thresholding.
import cv2
# Resize an image
resized = cv2.resize(image, (new_width, new_height))
# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur
blurred = cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)
# Apply thresholding
ret, thresholded = cv2.threshold(gray, threshold_value, max_value, cv2.THRESH_BINARY)Object Detection: OpenCV provides pre-trained models and functions for object detection, including popular algorithms like Haar cascades and deep learning-based methods like Single Shot MultiBox Detector (SSD) and You Only Look Once (YOLO).
import cv2
# Load a pre-trained Haar cascade
cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Perform face detection
faces = cascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)Video Capture and Processing: OpenCV allows capturing video from various sources and performing real-time video processing.
import cv2
# Open a video capture object
cap = cv2.VideoCapture(0) # 0 for the default camera
while True:
# Read a frame from the video
ret, frame = cap.read()
# Perform processing on the frame
# Display the processed frame
cv2.imshow('Frame', frame)
# Break the loop if 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture object and close windows
cap.release()
cv2.destroyAllWindows()Python, Pandas and Numpy
We have covered Python, Pandas and Numpy in detail as follows —
Downloading and Installing OpenCV
Downloading OpenCV:
- Visit the official OpenCV website at https://opencv.org/releases/.
- Choose the desired OpenCV version for your operating system (e.g., Windows, macOS, or Linux) and download the corresponding package.
- Extract the downloaded package to a suitable location on your computer.
Installing OpenCV:
- The installation process may vary depending on your operating system. Here, we’ll cover the installation steps for Windows using Python’s pip package manager.
- Open a command prompt or terminal window.
- Install OpenCV using pip by running the following command:
pip install opencv-python

Reading an Image
Reading an Image: To read an image using OpenCV, we can use the cv2.imread() function. The function takes the path to the image file as a parameter and returns a NumPy array representing the image.
Here’s the code to read an image and display it using OpenCV:
import cv2
# Read the image
image = cv2.imread('image.jpg')
# Display the image
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()In this code snippet, we use the cv2.imread() function to read the image file 'image.jpg' and store it in the variable image. The image file should be in the same directory as your Python script or provide the full path to the image file if it's located elsewhere.
We then display the image using cv2.imshow(). The first argument is the window name, and the second argument is the image to be displayed. We use cv2.waitKey(0) to wait until a key is pressed (0 indicates infinite wait), and finally, we use cv2.destroyAllWindows() to close the window when a key is pressed.
Displaying an Image
Load and display the image: To display an image, you need to load it using the cv2.imread() function, which takes the image file path as input. Then, you can use the cv2.imshow() function to display the loaded image.
import cv2
# Load an image
image = cv2.imread('image.jpg')
# Display the image
cv2.imshow('Image', image)
# Wait for a keyboard event and close the window
cv2.waitKey(0)
cv2.destroyAllWindows()Once you run this code, it will open a window displaying the image, and it will stay open until you close it or press any key on the keyboard.
Saving an Image
To save the image, you can use the cv2.imwrite() function. This function takes two arguments: the file path to save the image and the image object itself. The file path should include the desired filename and file extension. Here's an example of how to save the image as a JPEG file:
cv2.imwrite('path/to/save/image.jpg', image)Accessing Image Properties
Accessing image properties using Python and OpenCV allows you to retrieve information about an image, such as its dimensions, color channels, and data type.
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Access image properties
height, width, channels = image.shape
image_type = image.dtype
# Step 3: Print image properties
print("Image dimensions (height x width):", height, "x", width)
print("Number of channels:", channels)
print("Image data type:", image_type)- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We access the image properties by using the
shapeattribute of theimageobject. Theshapeattribute returns a tuple containing the height, width, and number of color channels of the image. We also retrieve the data type of the image using thedtypeattribute. - Finally, we print the image properties using
print()statements. The dimensions are printed asheight x width, the number of channels is printed, and the image data type is displayed.
Changing Color Space
Changing the color space of an image using Python and OpenCV allows you to convert the image from one color representation to another, such as RGB to grayscale or RGB to HSV.
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Convert the color space
converted_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Step 3: Display the original and converted images
cv2.imshow('Original Image', image)
cv2.imshow('Converted Image', converted_image)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We convert the color space of the image using the
cv2.cvtColor()function. This function takes two arguments: the input image and the color space conversion code. In this example, we convert the image from BGR (default for OpenCV) to grayscale using thecv2.COLOR_BGR2GRAYconversion code. You can explore other conversion codes for different color spaces in the OpenCV documentation. - We display the original and converted images using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the windows. - Finally, we use
cv2.destroyAllWindows()to close all the open windows.
Resizing the Image
Resizing an image using Python and OpenCV allows you to change the dimensions of the image while maintaining its aspect ratio.
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Convert the color space
converted_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Step 3: Display the original and converted images
cv2.imshow('Original Image', image)
cv2.imshow('Converted Image', converted_image)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We convert the color space of the image using the
cv2.cvtColor()function. This function takes two arguments: the input image and the color space conversion code. In this example, we convert the image from BGR (default for OpenCV) to grayscale using thecv2.COLOR_BGR2GRAYconversion code. You can explore other conversion codes for different color spaces in the OpenCV documentation. - We display the original and converted images using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the windows. - Finally, we use
cv2.destroyAllWindows()to close all the open windows.
Displaying Text
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Define the text parameters
text = "Hello, OpenCV!"
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1.5
color = (0, 255, 0) # BGR color tuple
thickness = 2
# Step 3: Add the text to the image
image_with_text = cv2.putText(image, text, (50, 50), font, font_scale, color, thickness, cv2.LINE_AA)
# Step 4: Display the image with text
cv2.imshow('Image with Text', image_with_text)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We define the text parameters: the text string, the font type (
cv2.FONT_HERSHEY_SIMPLEXin this example), the font scale, the color (specified as a BGR tuple), and the thickness of the text. - We add the text to the image using the
cv2.putText()function. This function takes several arguments: the image, the text string, the position of the text (specified as(x, y)coordinates), the font type, the font scale, the color, the thickness, and the line type (cv2.LINE_AAfor anti-aliased line). - We display the image with the added text using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the window. - Finally, we use
cv2.destroyAllWindows()to close the window.
Drawing a Line
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Define the line parameters
start_point = (50, 50)
end_point = (200, 200)
color = (0, 0, 255) # BGR color tuple
thickness = 2
# Step 3: Draw the line on the image
image_with_line = cv2.line(image, start_point, end_point, color, thickness)
# Step 4: Display the image with the line
cv2.imshow('Image with Line', image_with_line)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We define the line parameters: the start point of the line (
start_point), the end point of the line (end_point), the color of the line (specified as a BGR tuple), and the thickness of the line. - We draw the line on the image using the
cv2.line()function. This function takes several arguments: the image, the start point, the end point, the color, and the thickness. - We display the image with the drawn line using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the window. - Finally, we use
cv2.destroyAllWindows()to close the window.
Drawing a Circle
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Define the circle parameters
center_coordinates = (250, 250)
radius = 100
color = (0, 0, 255) # BGR color tuple
thickness = 2
# Step 3: Draw the circle on the image
image_with_circle = cv2.circle(image, center_coordinates, radius, color, thickness)
# Step 4: Display the image with the circle
cv2.imshow('Image with Circle', image_with_circle)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We define the circle parameters: the center coordinates of the circle (
center_coordinates), the radius of the circle, the color of the circle (specified as a BGR tuple), and the thickness of the circle's outline. - We draw the circle on the image using the
cv2.circle()function. This function takes several arguments: the image, the center coordinates, the radius, the color, and the thickness. - We display the image with the drawn circle using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the window. - Finally, we use
cv2.destroyAllWindows()to close the window.
Resize & Flip an Image
import cv2
# Step 1: Load the image
image = cv2.imread('path/to/your/image.jpg')
# Step 2: Resize the image
resized_image = cv2.resize(image, (500, 400))
# Step 3: Flip the image horizontally
flipped_image = cv2.flip(resized_image, 1)
# Step 4: Display the original, resized, and flipped images
cv2.imshow('Original Image', image)
cv2.imshow('Resized Image', resized_image)
cv2.imshow('Flipped Image', flipped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()- We import the
cv2module to access the OpenCV functions. - We load the image using the
cv2.imread()function and store it in theimagevariable. Replace'path/to/your/image.jpg'with the actual path to your image file. - We resize the image using the
cv2.resize()function. This function takes two arguments: the input image and the desired size of the output image. In this example, we resize the image to have a width of 500 pixels and a height of 400 pixels. - We flip the resized image horizontally using the
cv2.flip()function. This function takes two arguments: the input image and the flip code. In this example, we use a flip code of 1 to perform horizontal flipping. - We display the original, resized, and flipped images using the
cv2.imshow()function. The first argument is the window name, and the second argument is the image to be displayed. - We use
cv2.waitKey(0)to wait for a keyboard event (in this case, pressing any key) to close the windows. - Finally, we use
cv2.destroyAllWindows()to close all the open windows.
Deep Learning using Keras & TensorFlow in Python
We have covered in detail deep learning as follows —
Complete Keras and Tensorflow Series
Complete Pytorch Series
Face Detectors & Recognizers
import cv2
# Load the pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Load the pre-trained face recognizer
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trained_model.yml')
# Load the image
image = cv2.imread('image.jpg')
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Perform face detection
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)
# Iterate over detected faces
for (x, y, w, h) in faces:
# Draw a rectangle around the face
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Crop the face region from the image
face_roi = gray_image[y:y+h, x:x+w]
# Perform face recognition
label, confidence = recognizer.predict(face_roi)
# Get the predicted label name
if label == 0:
predicted_name = 'John Doe'
elif label == 1:
predicted_name = 'Jane Smith'
else:
predicted_name = 'Unknown'
# Display the predicted name and confidence
cv2.putText(image, f'{predicted_name} ({confidence:.2f})', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Display the image with detected faces and recognized names
cv2.imshow('Face Detection and Recognition', image)
cv2.waitKey(0)
cv2.destroyAllWindows()- We load the pre-trained face detector using
cv2.CascadeClassifierand the pre-trained face recognizer usingcv2.face.LBPHFaceRecognizer_create(). - The image is loaded using
cv2.imread()and converted to grayscale usingcv2.cvtColor(). - Face detection is performed using
face_cascade.detectMultiScale(). It detects multiple faces in the grayscale image and returns the bounding boxes of the detected faces. - The code then iterates over the detected faces and performs face recognition on each face region. The face region is cropped from the grayscale image and passed to the recognizer’s
predict()function. - Based on the predicted label, the code assigns a name to the face and displays it along with the confidence score using
cv2.putText(). - Finally, the image with the detected faces and recognized names is displayed using
cv2.imshow().
Object Detection, Tracking and Motion Analysis
import cv2
# Load the pre-trained Haar cascade classifiers for face and eyes
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
# Initialize the video capture
cap = cv2.VideoCapture(0)
# Initialize variables for motion analysis
motion_history = None
mot_threshold = 32
mot_duration = 1.0
while True:
# Read the current frame from the video capture
ret, frame = cap.read()
# Convert the frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Perform face detection
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
# Draw rectangles around detected faces and eyes
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
# Perform motion analysis
if motion_history is None:
motion_history = np.zeros_like(gray).astype(float)
prev_gray = gray
# Calculate the absolute difference between the current and previous frame
frame_diff = cv2.absdiff(prev_gray, gray)
# Apply a threshold to the frame difference
ret, motion_mask = cv2.threshold(frame_diff, mot_threshold, 1, cv2.THRESH_BINARY)
# Update the motion history
timestamp = cv2.getTickCount() / cv2.getTickFrequency()
cv2.motempl.updateMotionHistory(motion_mask, motion_history, timestamp, mot_duration)
# Normalize the motion history
motion_history_norm = np.uint8(np.clip((motion_history - (timestamp - mot_duration)) / mot_duration, 0, 1) * 255)
# Display the frames
cv2.imshow('Object Detection and Tracking', frame)
cv2.imshow('Motion Analysis', motion_history_norm)
# Check for the 'q' key to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Update the previous frame
prev_gray = gray
# Release the video capture and destroy all windows
cap.release()
cv2.destroyAllWindows()In this code snippet, we start by importing the necessary libraries and loading the pre-trained Haar cascade classifiers for face and eye detection. We then initialize the video capture using the webcam.
Inside the main loop, we read each frame from the video capture and convert it to grayscale. We perform face detection using the detectMultiScale function, which returns a list of bounding boxes for detected faces. We draw rectangles around the detected faces and eyes using the rectangle function.
Next, we perform motion analysis. We initialize the motion history and previous frame variables. We calculate the absolute difference between the current and previous frames and apply a threshold to obtain a binary motion mask. We update the motion history using the updateMotionHistory function. Finally, we normalize the motion history and display it.
Convolutional Neural Networks
import cv2
import numpy as np
import tensorflow as tf
# Load the pre-trained CNN model
model = tf.keras.applications.VGG16(weights='imagenet')
# Load the pre-trained image classification labels
with open('imagenet_labels.txt', 'r') as f:
labels = f.read().splitlines()
# Load and preprocess the input image
image = cv2.imread('image.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
image = np.expand_dims(image, axis=0)
image = tf.keras.applications.vgg16.preprocess_input(image)
# Perform image classification
predictions = model.predict(image)
top_predictions = tf.keras.applications.vgg16.decode_predictions(predictions, top=5)[0]
# Display the predicted labels
for _, label, confidence in top_predictions:
print(f'{label}: {confidence * 100:.2f}%')In this code snippet, we start by importing the necessary libraries, including OpenCV, NumPy, and TensorFlow. We load the pre-trained VGG16 model, which is a popular CNN architecture trained on the ImageNet dataset.
We also load the pre-trained image classification labels from a text file. Each line in the file corresponds to a label.
Next, we load and preprocess the input image. Here, we assume the image is stored as “image.jpg” in the current directory. We read the image using OpenCV, convert the color space to RGB (since OpenCV uses BGR by default), resize it to 224x224 pixels (VGG16 input size), and expand its dimensions to match the expected input shape of the VGG16 model. We also preprocess the image using the VGG16 preprocessing function.
After preprocessing, we pass the image through the pre-trained model using the predict method. This gives us the predicted probabilities for each class. We then use the decode_predictions function to map these probabilities to human-readable labels. In this example, we retrieve the top 5 predictions.
Finally, we display the predicted labels along with their corresponding confidence scores. The top predictions are printed to the console.
Build simple Image Classifiers in Python
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Load the dataset
image_paths = ['cat1.jpg', 'cat2.jpg', 'dog1.jpg', 'dog2.jpg']
labels = [0, 0, 1, 1] # 0 for cats, 1 for dogs
# Initialize lists to store the image features and labels
features = []
target = []
# Extract features from the images
for image_path in image_paths:
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (32, 32)) # Resize the image to a fixed size
# Flatten the image into a 1-dimensional array
image = image.flatten()
# Append the flattened image to the features list
features.append(image)
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
# Create and train the classifier
classifier = SVC()
classifier.fit(X_train, y_train)
# Predict the labels for the test set
y_pred = classifier.predict(X_test)
# Calculate the accuracy of the classifier
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")In this code snippet, we start by importing the necessary libraries, including OpenCV, NumPy, and scikit-learn. We define the image paths and corresponding labels for our dataset.
We then initialize lists to store the image features and labels. Inside the loop, we load each image using OpenCV, convert the color space to grayscale, and resize it to a fixed size (in this case, 32x32 pixels). We flatten the image into a 1-dimensional array using the flatten method and append it to the features list.
Next, we split the dataset into training and testing sets using the train_test_split function from scikit-learn.
After that, we create an instance of the Support Vector Machine (SVM) classifier from the SVC class and train it using the training data.
We then use the trained classifier to predict the labels for the test set.
Finally, we calculate the accuracy of the classifier by comparing the predicted labels with the true labels of the test set using the accuracy_score function from scikit-learn. The accuracy score is then printed to the console.
Build an OCR Reader
import cv2
import pytesseract
# Set the path to the Tesseract executable
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# Load the image
image = cv2.imread('text_image.jpg')
# Preprocess the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# Apply OCR to the preprocessed image
text = pytesseract.image_to_string(gray, config='--psm 6')
# Print the extracted text
print(text)In this code snippet, we start by importing the necessary libraries: OpenCV and pytesseract.
We then set the path to the Tesseract OCR executable using the tesseract_cmd variable. You'll need to specify the correct path to the Tesseract executable on your system.
Next, we load the image using OpenCV’s imread function. The image is assumed to be stored as "text_image.jpg" in the current directory.
After loading the image, we preprocess it for better OCR accuracy. First, we convert the image to grayscale using cvtColor function. Then, we apply a binary thresholding technique using threshold function to convert the image to black and white.
Finally, we apply the Tesseract OCR to the preprocessed image using image_to_string function from pytesseract. The config parameter can be used to specify additional Tesseract configuration options. In this example, we use --psm 6 which assumes a single uniform block of text.
The extracted text is stored in the text variable, and we print it to the console.
Neural Style Transfer Using OpenCV
Neural Style Transfer is a technique that allows you to apply the style of one image (the style image) to another image (the content image) using deep neural networks.
import cv2
import numpy as np
import tensorflow as tf
# Load the pre-trained VGG19 model
model = tf.keras.applications.VGG19(weights='imagenet', include_top=False)
# Define the content and style layers
content_layers = ['block4_conv2']
style_layers = ['block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1']
# Load the content and style images
content_image = cv2.imread('content_image.jpg')
style_image = cv2.imread('style_image.jpg')
# Preprocess the images
preprocess = tf.keras.applications.vgg19.preprocess_input
content_image = cv2.resize(content_image, (224, 224))
content_image = np.expand_dims(content_image, axis=0)
content_image = preprocess(content_image)
style_image = cv2.resize(style_image, (224, 224))
style_image = np.expand_dims(style_image, axis=0)
style_image = preprocess(style_image)
# Convert the images to tensors
content_tensor = tf.convert_to_tensor(content_image)
style_tensor = tf.convert_to_tensor(style_image)
# Extract the content and style features
def get_feature_representations(model, content_tensor, style_tensor):
content_outputs = []
style_outputs = []
for layer in content_layers:
content_outputs.append(model.get_layer(layer).output)
for layer in style_layers:
style_outputs.append(model.get_layer(layer).output)
content_model = tf.keras.models.Model(inputs=model.input, outputs=content_outputs)
style_model = tf.keras.models.Model(inputs=model.input, outputs=style_outputs)
content_features = content_model(content_tensor)
style_features = style_model(style_tensor)
return content_features, style_features
content_features, style_features = get_feature_representations(model, content_tensor, style_tensor)
# Calculate the Gram matrix
def gram_matrix(input_tensor):
result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor)
input_shape = tf.shape(input_tensor)
num_locations = tf.cast(input_shape[1] * input_shape[2], tf.float32)
return result / num_locations
# Calculate the style loss
def style_loss(style, generated):
style_gram = gram_matrix(style)
generated_gram = gram_matrix(generated)
channels = 3
size = 224 * 224
return tf.reduce_sum(tf.square(style_gram - generated_gram)) / (4.0 * (channels ** 2) * (size ** 2))
# Create the generated image as a trainable variable
generated_image = tf.Variable(content_image, dtype=tf.float32)
# Define the optimizer
optimizer = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)
# Define the total variation loss
def total_variation_loss(image):
x_deltas, y_deltas = tf.image.image_gradients(image)
return tf.reduce_mean(tf.abs(x_deltas)) + tf.reduce_mean(tf.abs(y_deltas))
# Perform Neural Style Transfer
@tf.function()
def train_step(image):
with tf.GradientTape() as tape:
content_features, style_features = get_feature_representations(model, content_tensor, image)
loss = tf.zeros(shape=())
for content, style in zip(content_features, style_features):
# Compute the content loss
loss += tf.reduce_mean(tf.square(content - content_features))
# Compute the style loss
loss += style_loss(style, style_features)
# Add total variation regularization
loss += total_variation_loss(image)
# Compute the gradients of the loss with respect to the generated image
gradients = tape.gradient(loss, image)
# Update the generated image
optimizer.apply_gradients([(gradients, image)])
# Clip the pixel values to the valid range
image.assign(tf.clip_by_value(image, clip_value_min=-1.0, clip_value_max=1.0))
# Number of iterations for optimization
num_iterations = 100
# Perform the Neural Style Transfer
for i in range(num_iterations):
train_step(generated_image)
# Convert the generated image tensor to a numpy array
generated_image = generated_image.numpy()
# Rescale the pixel values to the range [0, 255]
generated_image = generated_image.reshape((224, 224, 3))
generated_image = ((generated_image + 1) / 2) * 255
generated_image = np.clip(generated_image, 0, 255).astype(np.uint8)
# Save the generated image
cv2.imwrite('generated_image.jpg', generated_image)we define the train_step function that performs one optimization step using the content and style features. Within the function, we compute the content loss, style loss, and total variation loss. We then compute the gradients of the loss with respect to the generated image and update the generated image using the Adam optimizer.
We specify the number of iterations for optimization and loop over them to perform the Neural Style Transfer. In each iteration, we call the train_step function with the generated image.
After the optimization process, we convert the generated image tensor to a numpy array and rescale the pixel values to the range [0, 255]. We then save the generated image using OpenCV’s imwrite function.
Multi Object Detection in OpenCV
import cv2
# Load the pre-trained model
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# Load the classes
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# Set the input image and output layer names
image = cv2.imread('image.jpg')
height, width = image.shape[:2]
blob = cv2.dnn.blobFromImage(image, 1/255, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
output_layers = net.getUnconnectedOutLayersNames()
# Forward pass through the network
outputs = net.forward(output_layers)
# Process the outputs
class_ids = []
confidences = []
boxes = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Calculate the top-left corner of the bounding box
x = int(center_x - w / 2)
y = int(center_y - h / 2)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# Apply non-maximum suppression
indices = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold=0.5, nms_threshold=0.4)
# Draw the bounding boxes and labels
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
label = classes[class_ids[i]]
confidence = confidences[i]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, f'{label} {confidence:.2f}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the output image
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()In this code snippet, we start by loading the pre-trained model using the readNetFromDarknet function, which reads the YOLOv3 model configuration file ('yolov3.cfg') and the corresponding weights file ('yolov3.weights').
We also load the class names from the ‘coco.names’ file, which contains the names of the objects that the model can detect.
Next, we load the input image and prepare it for inference. We resize the image to the desired input size of the YOLOv3 model (416x416 pixels) and create a blob from the image using blobFromImage function. The blob is then set as the input to the network.
After setting the input, we perform a forward pass through the network to obtain the output predictions. We retrieve the unconnected output layer names using getUnconnectedOutLayersNames method and then pass them to the forward method.
Black and white Images to color using Caffe
To convert black and white images to color using Caffe, you can utilize the “Colorization” model provided by Caffe. This model is trained to predict the colorization of grayscale images.
import caffe
import numpy as np
import cv2
# Load the pre-trained model and configure Caffe
caffe.set_mode_gpu()
net = caffe.Net('colorization_deploy_v2.prototxt', 'colorization_release_v2.caffemodel', caffe.TEST)
# Load the black and white image
bw_image = cv2.imread('bw_image.jpg', 0)
# Resize the image to match the input size of the network
resized_image = cv2.resize(bw_image, (224, 224))
# Convert the image to Lab color space
lab_image = cv2.cvtColor(resized_image, cv2.COLOR_GRAY2LAB)
# Split the Lab image into L and ab channels
L_channel = lab_image[:, :, 0]
# Subtract the mean value of the L channel (50) as required by the model
L_channel -= 50
# Reshape the L channel to match the network input shape
reshaped_L = L_channel.reshape(1, 1, 224, 224)
# Set the input data for the network
net.blobs['data_l'].data[...] = reshaped_L
# Forward pass through the network
net.forward()
# Retrieve the generated ab channels from the network output
ab_channels = net.blobs['class8_ab'].data[0, :, :, :]
# Resize the ab channels to match the size of the input image
resized_ab = cv2.resize(ab_channels.transpose((1, 2, 0)), (resized_image.shape[1], resized_image.shape[0]))
# Combine the L channel and ab channels to form the Lab image
lab_result = np.concatenate((L_channel[:, :, np.newaxis], resized_ab), axis=2)
# Convert the Lab image to BGR color space
color_result = cv2.cvtColor(lab_result, cv2.COLOR_LAB2BGR)
# Convert the color image to the original image size
final_result = cv2.resize(color_result, (bw_image.shape[1], bw_image.shape[0]))
# Display the colorized image
cv2.imshow('Colorized Image', final_result)
cv2.waitKey(0)
cv2.destroyAllWindows()In this code snippet, we start by loading the pre-trained “Colorization” model in Caffe using the Net class. We configure Caffe to run on the GPU using set_mode_gpu().
We then load the black and white image using cv2.imread() function and resize it to match the input size of the network (224x224 pixels).
Next, we convert the resized image from grayscale to Lab color space using cv2.cvtColor() function.
After converting to Lab color space, we extract the L channel (black and white channel) from the Lab image.
To prepare the L channel for the network input, we subtract the mean value of the L channel (50) as required by the model.
The L channel is reshaped to match the network input shape, and we set it as the input data for the network using net.blobs['data_l'].data[...].
We then perform a forward pass through the network using net.forward().
After the forward pass, we retrieve the generated ab channels from the network output and resize them to match the size of the input image.
The L channel and resized ab channels are then combined to form the Lab image using np.concatenate().
Finally, we convert the Lab image to BGR.
RGB channels
RGB channels represent the three primary colors (red, green, and blue) that make up an image. In OpenCV, you can easily split an image into its individual RGB channels and manipulate them separately. Here’s a code snippet that demonstrates how to work with RGB channels in OpenCV using Python:
import cv2
import numpy as np
# Load the image
image = cv2.imread('image.jpg')
# Split the image into RGB channels
blue_channel, green_channel, red_channel = cv2.split(image)
# Show the individual channels
cv2.imshow('Blue Channel', blue_channel)
cv2.imshow('Green Channel', green_channel)
cv2.imshow('Red Channel', red_channel)
# Merge the channels back together
merged_image = cv2.merge([blue_channel, green_channel, red_channel])
# Show the merged image
cv2.imshow('Merged Image', merged_image)
# Manipulate the channels (e.g., increase the red channel)
red_channel = cv2.add(red_channel, 50)
# Merge the modified channels back together
modified_image = cv2.merge([blue_channel, green_channel, red_channel])
# Show the modified image
cv2.imshow('Modified Image', modified_image)
# Wait for a key press and then close all windows
cv2.waitKey(0)
cv2.destroyAllWindows()In this code snippet, we start by loading an image using cv2.imread().
Next, we use cv2.split() to split the image into its individual RGB channels: blue_channel, green_channel, and red_channel.
We then display each channel using cv2.imshow(). This will show separate windows for the blue, green, and red channels.
To merge the channels back together, we use cv2.merge() and pass the individual channels as a list.
We display the merged image using cv2.imshow().
To manipulate the channels individually, we can perform various operations on them. In this example, we increase the intensity of the red channel by adding 50 to its pixel values using cv2.add().
Finally, we merge the modified channels back together to create the modified image and display it using cv2.imshow().
Projects Coming soon!
That’s it for now. Keep checking this post every day to see new projects.
Let me know if you have questions in the comment section below. Subscribe/ Follow, Like/Clap as it would encourage me to write more in my free time
Stay Tuned and Keep coding!!
Read More —
11 most important System Design Base Concepts
6. Networking, How Browsers work, Content Network Delivery ( CDN)
13. System Design Template — How to solve any System Design Question
System Design Case Studies — In Depth
Design Instagram
Design Netflix
Design Reddit
Design Amazon
Design Messenger App
Design Twitter
Design URL Shortener
Design Dropbox
Design Youtube
Design API Rate Limiter
Design Web Crawler
Design Amazon Prime Video
Design Facebook’s Newsfeed
Design Yelp
Design Uber
Design Tinder
Design Tiktok
Design Whatsapp
Most Popular System Design Questions
Mega Compilation : Solved System Design Case studies
Complete Data Structures and Algorithm Series
Some of the other best Series —
30 days of Data Structures and Algorithms and System Design Simplified
Data Science and Machine Learning Research ( papers) Simplified **
100 days : Your Data Science and Machine Learning Degree Series with projects
Complete Data Visualization and Pre-processing Series with projects
Exceptional Github Repos — Part 1
Exceptional Github Repos — Part 2
Tech Newsletter —
If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :
For Python Projects —
For complete 60 days of Data Science and ML : Day 1 — Day 60 : Quick Recap of 60 days of Data Science and ML
Follow for more updates.
For other projects, tune to —
Build Machine Learning Pipelines( With Code)
Recurrent Neural Network with Keras
Clustering Geolocation Data in Python using DBSCAN and K-Means
Facial Expression Recognition using Keras
Hyperparameter Tuning with Keras Tuner
Custom Layers in Keras






