Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
ROS 2 Practical - Lesson 8
OpenCV fundamentals, from pixels to pedestrian detection
Laplacian, Sobel, CannyHOG descriptorsimport cv2 as cv
import numpy as np
print(f"OpenCV Version: {cv.__version__}")OpenCV version before anything else.NumPy arrays: img.shape = (height, width, channels)def rescale(frame, scale=0.75):
height = int(frame.shape[0] * scale)
width = int(frame.shape[1] * scale)
return cv.resize(frame, (width, height), interpolation=cv.INTER_AREA)0.75 keeps 75% of the original size.gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)3x3, 5x5, 7x7); a larger kernel means more blurblur = cv.GaussianBlur(img, (7, 7), cv.BORDER_DEFAULT)canny = cv.Canny(img, 125, 175)
kernel = np.ones((3, 3), np.uint8)
dilated = cv.dilate(canny, kernel, iterations=1) # expand white regions
eroded = cv.erode(canny, kernel, iterations=1) # shrink white regionsdilate expands white regions, erode shrinks them.cv.CV_64F to preserve negative values before taking abs().lap = cv.Laplacian(gray, cv.CV_64F)
lap_abs = np.uint8(np.absolute(lap))X/Y gradients that can be combined into one edge map.sobelx = cv.Sobel(gray, cv.CV_64F, 1, 0) # vertical edges
sobely = cv.Sobel(gray, cv.CV_64F, 0, 1) # horizontal edges
combined = cv.bitwise_or(np.uint8(np.absolute(sobelx)),
np.uint8(np.absolute(sobely)))Gaussian Blur
Gradient Calculation
Non-Max Suppression
Double Thresholding
Hysteresis Edge Tracking
canny = cv.Canny(gray, 150, 175)_, thresh_binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)adaptive_mean = cv.adaptiveThreshold(
gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY,
11, # block size (must be odd)
9) # C: constant subtracted from the mean11 is the block size (must be odd); 9 is C, subtracted from the local mean.| Global | Adaptive | |
|---|---|---|
| Threshold | Single value | Local values |
| Best for | Uniform lighting | Varying lighting |
| Speed | Faster | Slower |
Compute Gradients
Per-Cell Histograms
Normalize Across Blocks
Feature Vector
SVM Classify
hog = cv.HOGDescriptor()
hog.setSVMDetector(cv.HOGDescriptor_getDefaultPeopleDetector())
(regions, weights) = hog.detectMultiScale(
image,
winStride=(4, 4), # sliding window step (smaller = more detections, slower)
padding=(4, 4), # padding around detected regions
scale=1.05) # image pyramid scale factorwinStride smaller means more detections but slower; scale is the image pyramid factor.Applying HOG
cap = cv2.VideoCapture('streetup.mp4')
while cap.isOpened():
ret, image = cap.read()
if not ret:
break
image = imutils.resize(image, width=min(400, image.shape[1]))
(regions, _) = hog.detectMultiScale(image, winStride=(4, 4),
padding=(4, 4), scale=1.05)
for (x, y, w, h) in regions:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow('Pedestrian Detection', image)
if cv2.waitKey(25) & 0xFF == ord('q'):
breakhog descriptor from the previous slide, run frame by frame on streetup.mp4.Camera Matrix: Distortion Coefficients:
[fx 0 cx] [k1, k2, p1, p2, k3]
[0 fy cy] k1,k2,k3 = radial
[0 0 1] p1,p2 = tangentialCapture Checkerboard Images
Detect Corners
Refine Corners
3D Coordinates
calibrateCamera
CHECKERBOARD = (6, 9) # internal corners
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
for fname in glob.glob('./images/*.jpg'):
gray = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, None)
if ret:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
objpoints, imgpoints, gray.shape[::-1], None, None)| Topic | Key Functions |
|---|---|
| Basic ops | imread, resize, cvtColor, GaussianBlur |
| Edge detection | Laplacian, Sobel, Canny |
| Thresholding | threshold, adaptiveThreshold |
| HOG detection | HOGDescriptor, detectMultiScale |
| Calibration | findChessboardCorners, calibrateCamera |
Canny, being multi-stage, generally gives cleaner edges than Laplacian or Sobel alonewinStride and scale to trade speed for accuracyMahmoud Abas|Computer Vision Lab: Image Processing & Object Detection