1. Image Processing & Detection Pipeline
The diagram below displays the computer vision pipeline. The input image goes through classical processing steps (blur, Canny edge detection, thresholding) to extract features, while the Haar Cascade classifier runs face detection to draw bounding boxes.
Input Image
RGB Pixels
Process
2. OpenCV Filters
GaussianBlur / Canny
Binary Threshold
Detect
3. Haar Cascade
haarcascade_xml
detectMultiScale()
Sliding window scan
4. Output
canny_edges.png
face_output.png
Bounding boxes
2. Part 1: Step-by-Step Action Items & Key Execution Steps
STEP 1
Activate Python Virtual Environment
Point the terminal execution environment to the course conda sandbox environment.
$ conda activate ds_ai_ml
This targets active python libraries to the isolated virtual sandbox.
STEP 2
Create Project Folders inside Linux VM
Create a dedicated folder for the project files inside your guest VM home folder directory.
$ mkdir -p ~/Projects/opencv_app && cd ~/Projects/opencv_app
This sets up the working directory layout for the OpenCV code files.
STEP 3
Install OpenCV-Python via Pip
Install OpenCV libraries inside the active conda session.
$ pip install opencv-python numpy matplotlib requests
This installs the core OpenCV library, numpy arrays, and plotting tools.
STEP 4
Download Haar Cascade XML File
Download the pre-trained Haar Cascade face detection XML file from the OpenCV repository.
$ wget https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml
This downloads the XML file containing the features to run the face detection classifier.
STEP 5
Create image processing script file in VS Code
Launch VS Code and create the OpenCV pipeline script file.
Launch VS Code via terminal "code ." -> New File -> Type: cv_pipeline.py -> Paste Python code -> Save file
This registers the image processing operations and face detection loops in `cv_pipeline.py`.
STEP 6
Run and Verify the CV pipeline
Execute the script to run image processing operations and face detection.
$ python cv_pipeline.py
This runs Canny edge detection, thresholding, and face detection, saving the processed images to disk.
STEP 7
Open and verify generated image outputs
Open the output images using the default Linux desktop photo viewer to review the results.
$ xdg-open processed_filters.png && xdg-open face_detected.png
This command loads the image viewer application on the VM desktop to display the output images.
3. CV Execution Flow
The flowchart below outlines the computer vision execution flow. It details the steps from raw image loading and applying filters to running face detection and saving output images.
1. Load Image
Read input image
from workspace path
cv2.imread()
2. Apply Filters
Calculate Canny edges
and thresholds
cv2.Canny()
3. Load XML
Load cascade XML
detector weights
CascadeClassifier()
4. Detect Faces
Detect face bounds
in input image
detectMultiScale()
5. Save Image
Write output images
to workspace path
cv2.imwrite()
4. Part 2: Complete Deliverable Assets & Production Templates
To run the computer vision pipeline, we need the Python script file. Below is a line-by-line explanation of the code, followed by the combined template.
Step-by-Step Code Construction
Lines 1 - 5
Import OpenCV and Numpy modules
Include OpenCV, Numpy arrays, and matplotlib plotting tools in the script.
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
These imports pull standard OpenCV image processing APIs, numpy matrices, and plotting libraries.
Lines 6 - 15
Generate Synthetic Image
Create a synthetic image with geometric shapes to apply CV filters on.
img = np.zeros((300, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (50, 50), (250, 250), (255, 255, 255), -1)
cv2.circle(img, (150, 150), (50, 50, 50), (0, 0, 0), -1)
cv2.imwrite("synthetic_input.png", img)
This generates a 300x300 pixel RGB image with a white square and black circle to test edge detection filters.
Lines 16 - 28
Apply Classical Image Filters
Apply Gaussian blurs, Canny edge detection, and binary thresholding to the generated image.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
_, thresholded = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)
This converts the image to grayscale, applies a Gaussian blur, runs Canny edge detection, and applies binary thresholding.
Lines 29 - 42
Run Haar Cascade Face Detection
Load the XML classifier weights and run face detection on a dummy face matrix.
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
dummy_face = np.zeros((200, 200, 3), dtype=np.uint8)
# Draw circles representing eyes/mouth to simulate a face
cv2.circle(dummy_face, (100, 100), (50), (255, 255, 255), -1)
faces = face_cascade.detectMultiScale(dummy_face, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(dummy_face, (x, y), (x+w, y+h), (0, 255, 0), 2)
This loads the Cascade XML file, runs face detection on a dummy face image, and draws bounding boxes around detected regions.
Production templates
1. Python script (Save as ~/Projects/opencv_app/cv_pipeline.py):
# cv_pipeline.py - Image filters and Haar Cascade face detection
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
def main ():
print("=== Part 1: Generating Synthetic Image and Applying Filters ===" )
# Create 300x300 RGB image with white square and black circle
img = np.zeros((300, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (50, 50), (250, 250), (255, 255, 255), -1)
cv2.circle(img, (150, 150), 50, (0, 0, 0), -1)
# 1. Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 2. Gaussian Blur
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 3. Canny Edge Detection
edges = cv2.Canny(blurred, 50, 150)
# 4. Binary Thresholding
_, thresh = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)
# Save processing plots
plt.style.use('dark_background')
fig, axes = plt.subplots(1, 4, figsize=(15, 5))
axes[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
axes[0].set_title("Input Image")
axes[1].imshow(gray, cmap="gray")
axes[1].set_title("Grayscale")
axes[2].imshow(edges, cmap="gray")
axes[2].set_title("Canny Edges")
axes[3].imshow(thresh, cmap="gray")
axes[3].set_title("Thresholded")
for ax in axes:
ax.axis("off")
plt.tight_layout()
filters_filename = "processed_filters.png"
plt.savefig(filters_filename, facecolor="#0f172a", edgecolor="none")
print(f"Classical filters plot saved: {filters_filename}")
print("\n=== Part 2: Running Haar Cascade Face Detection ===" )
cascade_path = "haarcascade_frontalface_default.xml"
if not os.path.exists(cascade_path):
print("Haar Cascade XML missing. Make sure to download it using wget in step 4." )
return
face_cascade = cv2.CascadeClassifier(cascade_path)
# Create dummy face matrix (white circle on black background)
dummy_face = np.zeros((300, 300, 3), dtype=np.uint8)
cv2.circle(dummy_face, (150, 120), 60, (255, 255, 255), -1) # Head outline
cv2.circle(dummy_face, (120, 100), 10, (0, 0, 0), -1) # Left Eye
cv2.circle(dummy_face, (180, 100), 10, (0, 0, 0), -1) # Right Eye
cv2.ellipse(dummy_face, (150, 160), (30, 10), 0, 0, 180, (0, 0, 0), -1) # Mouth
gray_face = cv2.cvtColor(dummy_face, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray_face, scaleFactor=1.05, minNeighbors=2, minSize=(50, 50))
print(f"Faces detected: {len(faces)}")
for (x, y, w, h) in faces:
cv2.rectangle(dummy_face, (x, y), (x+w, y+h), (0, 255, 0), 3)
print(f" - Bounding Box: X={x}, Y={y}, Width={w}, Height={h}")
face_output_filename = "face_detected.png"
cv2.imwrite(face_output_filename, dummy_face)
print(f"Face detection plot saved: {face_output_filename}")
print("\n=== Computer Vision Project Successfully Complete! ===" )
if __name__ == "__main__" :
main()
5. Deliverables Summary
Verify that the following configurations and outputs exist inside your project workspace.
Created Files / Templates
~/Projects/opencv_app/cv_pipeline.py - OpenCV pipeline script file.
~/Projects/opencv_app/haarcascade_frontalface_default.xml - Pretrained Haar weights file.
~/Projects/opencv_app/processed_filters.png - Saved classical filters plot.
~/Projects/opencv_app/face_detected.png - Face detection bounding boxes plot.
Verification Artifacts / Execution Proof
Grayscale conversion, Gaussian blurring, Canny edge detection, and thresholding output plots saved to disk.
Haar Cascade classifier loaded successfully without path errors.
Correct bounding boxes drawn around detected regions in output images.
6. Closing Explanation: Why We Did This & What It Accomplishes
Architectural Intent & Operational Impact
Why We Did This
Grayscale conversion reduces image dimensions, enabling faster processing.
Canny edge detection uses gradient thresholds to extract shape borders and contours.
Haar Cascade classifiers use sliding windows to detect faces in real-time, even on low-CPU VMs.
What This Accomplishes
Loads raw images and applies classical filters.
Runs face detection using a pre-trained Haar Cascade classifier.
Saves the processed outputs and bounding box plots to disk.