Setup Project 6

Computer Vision Environment Setup

Install OpenCV image-processing libraries inside your virtual sandbox, configure host-to-guest USB webcam controller pathways, download pretrained YOLOv4 networks, and run diagnostic image filters.

Environment
OpenCV / Linux VM / Webcam
Difficulty
Intermediate (2/5)
Course Module
Computer Vision
Deliverables
Grayscale Saved Images & Model Load Logs
Webcam hardware virtualization: To access your physical host computer's integrated webcam inside the VirtualBox Ubuntu VM, you must download the VirtualBox Extension Pack on the Windows Host, enable USB 2.0/3.0 controllers in VM Settings, and select the device under the VM menu Devices -> Webcams -> [Your Webcam]. This guide details how to configure this webcam integration or fall back to static image processing.
1. System Architecture & Process Workflow

The diagram below displays the computer vision ingestion flow. Input frames are retrieved from the physical webcam interface (routed through USB VirtualBox links) or static files, converted into pixel coordinate matrices, transformed into BGR/RGB matrices via OpenCV, and parsed through deep neural layer weight definitions.

Image Ingestion Webcam Video Link Static File (dog.jpg) cv2.imread OpenCV Processing Engine Color Matrix: BGR -> RGB cv2.cvtColor() Filters: Gaussian Blur, Canny DNN Blob YOLOv4 Object Detector Network Layers Config readNetFromDarknet() COCO Weights (244MB)
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 points terminal execution to the isolated sandbox, enabling target module installations.
STEP 2

Install OpenCV Modules via Pip

Install the OpenCV core python bindings library inside the active conda session.

$ pip install opencv-python opencv-python-headless matplotlib numpy
This downloads the computer vision framework wrapper binaries, loading dependencies for mathematical matrix and plotting outputs.
STEP 3

Install VirtualBox Extension Pack on Windows Host

Install the Extension Pack in your Windows VirtualBox Manager to enable USB virtualization filters.

Open host browser -> Go to https://www.virtualbox.org/wiki/Downloads -> Download "VirtualBox Extension Pack" -> Double-click to install -> Accept terms
This action installs USB driver interfaces in VirtualBox, enabling you to forward your laptop's webcam to the VM.
STEP 4

Configure VM Settings for USB forward

Stop the virtual machine session and check the configuration templates in VirtualBox settings to mount USB endpoints.

Shutdown Ubuntu VM -> Open VirtualBox Manager -> Click "Ubuntu" -> Click Settings -> Click USB -> Check "Enable USB Controller" -> Select "USB 2.0 (EHCI) Controller" -> Click OK
This allocates VM hardware registers to map USB devices from the host computer system.
STEP 5

Mount Host Webcam inside Ubuntu Session

Boot the virtual machine and route the camera hardware stream through the devices menu dashboard.

Start Ubuntu VM -> Click "Devices" in VM Top Menu Bar -> Hover over "Webcams" -> Check box next to your Web Camera name
This action links the camera hardware pipeline directly to `/dev/video0` inside the guest Linux operating system.
STEP 6

Download YOLOv4 Config and Weights Files

Fetch pre-trained network topologies and weight parameters using wget utility commands.

$ mkdir -p ~/CV_Project && cd ~/CV_Project $ wget https://github.com/AlexeyAB/darknet/releases/download/yolov4/yolov4.weights $ wget https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4.cfg $ wget https://raw.githubusercontent.com/AlexeyAB/darknet/master/data/coco.names $ wget https://raw.githubusercontent.com/AlexeyAB/darknet/master/data/dog.jpg
This command downloads configuration maps, COCO labels, trained weights, and a test image to the project folder.
STEP 7

Save Python CV Diagnostic Script

Open a document editor inside the terminal and write your verification script code.

$ nano ~/verify_cv.py
This opens nano editor. Paste the verification script from Part 2 below, press **Ctrl + O** and **Enter** to save, and **Ctrl + X** to exit.
STEP 8

Execute verification script

Run the validation script using the python engine to verify computer vision operations work.

$ python ~/verify_cv.py
This runs the script. You should see validation outputs confirming the image file was read, grayscale filter was saved, and YOLO network model was loaded.
3. Operational Pipeline Architecture

The flowchart below outlines the computer vision setup pipeline. It shows the steps from installing dependencies and configuring VirtualBox USB webcam routing to fetching YOLO weights and executing the Python verification script.

1. Install CV Install opencv via pip tool pip install 2. VM USB Link Enable USB settings and select webcam VirtualBox GUI 3. Download net Fetch YOLO weights and configurations wget yolov4 4. Save Script Write diagnostic python logic verify_cv.py 5. Run Check Verify model load and grayscale filter python execution
4. Part 2: Complete Deliverable Assets & Production Templates

To verify the OpenCV installation, we will write a Python script that loads an image, converts it to grayscale, saves it, and loads a pretrained YOLOv4 network. Below is a line-by-line explanation of the code, followed by the combined script.

Step-by-Step Code Construction

Lines 1 - 3

Import CV and System Modules

Include OpenCV and OS libraries to write file and image operations.

import cv2 import os import numpy as np
These imports import the OpenCV framework module, folder diagnostic check utilities, and matrix array libraries.
Lines 4 - 8

Load and Convert Image Arrays

Read the sample test image using OpenCV and apply color matrix conversion filters.

image_path = os.path.expanduser("~/CV_Project/dog.jpg") original_img = cv2.imread(image_path) print(f"Image Resolution: {original_img.shape}") grayscale_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
This parses the file path, loads the image coordinates, and converts the color matrix BGR channels to standard grayscale.
Lines 9 - 11

Save Grayscale Image Copy

Write the grayscale image copy to the local project folder disk directory.

output_path = os.path.expanduser("~/CV_Project/dog_grayscale.jpg") cv2.imwrite(output_path, grayscale_img) print(f"Grayscale image saved successfully to {output_path}")
This command writes the new grayscale matrix back as a JPG file to the output directory path.
Lines 12 - 18

Load Pretrained YOLOv4 Network Model

Initialize the OpenCV DNN module, loading YOLO weights and network configuration layers.

weights = os.path.expanduser("~/CV_Project/yolov4.weights") config = os.path.expanduser("~/CV_Project/yolov4.cfg") print("Loading YOLOv4 Network...") net = cv2.dnn.readNetFromDarknet(config, weights) print("YOLOv4 Network loaded successfully!")
This locates the weights and configs, compiles the DNN layer maps, and loads the network model structures into local memory.

Combined OpenCV Verification Script

Save the consolidated blocks above as ~/verify_cv.py and execute it inside the active ds_ai_ml environment:

# verify_cv.py - Computer Vision Verification Script import cv2 import os import numpy as np def main(): print("=== Computer Vision & OpenCV Diagnostics ===") project_dir = os.path.expanduser("~/CV_Project") image_file = os.path.join(project_dir, "dog.jpg") grayscale_file = os.path.join(project_dir, "dog_grayscale.jpg") weights_file = os.path.join(project_dir, "yolov4.weights") config_file = os.path.join(project_dir, "yolov4.cfg") # 1. Image Read & Resolution Checks if not os.path.exists(image_file): print(f"ERROR: Sample image not found at {image_file}. Run step 6 commands first.") return img = cv2.imread(image_file) height, width, channels = img.shape print(f"Successfully read image: {image_file}") print(f" - Resolution: {width}x{height} pixels") print(f" - Color Channels: {channels} (BGR)") # 2. Image Grayscale Conversion Filter gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imwrite(grayscale_file, gray) print(f"Grayscale transformation completed. File saved: {grayscale_file}") # 3. OpenCV DNN YOLOv4 Model Loading Verification if not os.path.exists(weights_file) or not os.path.exists(config_file): print("ERROR: YOLO files missing. Skiped model load verification.") return print("Loading pre-trained YOLOv4 network model layers into RAM...") net = cv2.dnn.readNetFromDarknet(config_file, weights_file) # Configure computation backend (fallback to CPU for standard VM compatibility) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) print("Model architecture successfully validated and allocated.") print("\n=== Computer Vision Environment Successfully Verified! ===") if __name__ == "__main__": main()
5. Deliverables Summary

Verify that the following configurations and outputs exist inside your project workspace.

Created Files / Templates

  • ~/verify_cv.py - Verification python script file.
  • ~/CV_Project/dog_grayscale.jpg - Filtered grayscale copy image file.

Verification Artifacts / Execution Proof

  • Console logs confirming image resolution shape specs.
  • Grayscale file created and saved in the ~/CV_Project folder.
  • Successful loading of YOLOv4 weights in the terminal log files.
6. Closing Explanation: Why We Did This & What It Accomplishes

Architectural Intent & Operational Impact

Why We Did This

What This Accomplishes