OpenCV Python Practicals: Read, Grayscale, Crop, Resize & Edges

⚑ Direct Answer & Key Takeaway

In CBSE Class 10 AI (Code 417) 50-mark practical exams, OpenCV (`cv2`) represents loaded images as NumPy arrays shaped `(height, width, channels)` in **BGR** order rather than RGB. Core lab steps use `cv2.imread()` to load files, `cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)` for grayscale conversion, `cv2.resize(img, (width, height))` for scaling, NumPy slicing `img[y1:y2, x1:x2]` for cropping, and `cv2.Canny(gray, low, high)` to detect object edges.

1. Loading Images & BGR vs RGB Color Spaces

Every CBSE Class 10 (Code 417) OpenCV lab starts with `import cv2` and `img = cv2.imread('photo.jpg')`. Unlike Matplotlib or Pillow, which store color pixels in Red-Green-Blue (`RGB`) order, OpenCV loads standard color images in Blue-Green-Red (`BGR`) order by default. If you plot an OpenCV image directly inside Matplotlib without converting via `cv2.cvtColor(img, cv2.COLOR_BGR2RGB)`, human faces turn bluish and red apples look cyan. Inspecting `img.shape` returns a tuple `(rows, cols, 3)` where rows equal image height and columns equal width. When a file path is misspelled, `cv2.imread()` silently returns `None` instead of throwing a file error, causing downstream crashes like `AttributeError` or empty-frame assertions. Always verify `img is not None` before invoking `cv2.cvtColor()` to convert the image to single-channel grayscale (`COLOR_BGR2GRAY`) for faster processing.

  • cv2.imread(path, 1) loads 3-channel BGR; cv2.imread(path, 0) loads 1-channel grayscale directly.
  • Grayscale images reduce 2D shape from (H, W, 3) to (H, W), cutting pixel volume by 3x.
  • Convert BGR to RGB with cv2.COLOR_BGR2RGB before displaying via plt.imshow().

2. Resizing & Cropping Without Swapping Axes

Students frequently lose practical marks by mixing up coordinate order between NumPy array slicing and `cv2.resize()`. In NumPy slicing, row indices come first and column indices come second, so cropping a Region of Interest (`ROI`) requires `cropped = img[y1:y2, x1:x2]`β€”vertical `y` range before horizontal `x` range. Conversely, OpenCV's `cv2.resize(img, (new_width, new_height))` expects a `(width, height)` tuple, matching `x` before `y` just like `img.shape[1]` before `img.shape[0]`. Scaling down high-resolution images uses `cv2.INTER_AREA` interpolation to avoid jagged aliasing, while enlarging small thumbnails uses `cv2.INTER_CUBIC` or `cv2.INTER_LINEAR`. Because slicing creates a view of the original array, calling `.copy()` when modifying a cropped region prevents accidental edits to the source photograph during annotation or augmentation tasks.

  • Crop syntax: img[y_start:y_end, x_start:x_end] (rows first, columns second).
  • Resize syntax: cv2.resize(img, (width, height)) (columns first, rows second).
  • Display windows in desktop labs need cv2.waitKey(0) followed by cv2.destroyAllWindows().

3. Canny Edge Detection & Threshold Tuning

Edge detection isolates object silhouettes while stripping away lighting clutter and flat background textures. In `cv2.Canny(gray, threshold1, threshold2)`, OpenCV executes a four-stage pipeline: Gaussian smoothing to suppress camera sensor noise, Sobel gradient calculation for intensity magnitude and direction, non-maximum suppression to thin thick gradients into single-pixel lines, and hysteresis thresholding. Hysteresis relies on two numeric cutoffs: gradients above `threshold2` (upper threshold) are accepted immediately as strong edges, while gradients below `threshold1` (lower threshold) are discarded. Intermediate gradients between `threshold1` and `threshold2` survive only if they connect directly to a strong edge pixel. Practical guidelines set `threshold2` roughly two to three times `threshold1`, such as `(50, 150)` or `(100, 200)`. Converting to grayscale and applying a `5Γ—5` `cv2.GaussianBlur` beforehand produces cleaner contours for shape counting.

  • Canny Stage 1: Gaussian blur removes pixel noise that would trigger false edges.
  • Hysteresis keeps weak edges only when linked to strong edges above threshold2.
  • Use cv2.imwrite('edges.png', edges) to save processed outputs in school lab files.

4. OpenCV Pipeline Simulation: Grayscale, Crop, Resize & Edge Detection

try:
    import cv2
    import numpy as np
    HAS_CV2 = True
except ImportError:
    HAS_CV2 = False

if HAS_CV2:
    img = np.zeros((6, 6, 3), dtype=np.uint8)
    img[:, 3:] = [200, 200, 200]
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cropped = gray[1:5, 1:5]
    resized = cv2.resize(cropped, (2, 2), interpolation=cv2.INTER_AREA)
    edges = cv2.Canny(gray, 50, 150)
    print("BGR shape:", img.shape)
    print("Gray shape:", gray.shape)
    print("Cropped shape:", cropped.shape)
    print("Resized pixels:", resized.tolist())
    print("Canny edges shape:", edges.shape, "| Edge found:", bool(edges.max() > 0))
else:
    img = [[[0, 0, 0] if c < 3 else [200, 200, 200] for c in range(6)] for _ in range(6)]
    gray = [[round(0.114 * p[0] + 0.587 * p[1] + 0.299 * p[2]) for p in row] for row in img]
    cropped = [row[1:5] for row in gray[1:5]]
    resized = [
        [(cropped[r][c] + cropped[r][c + 1] + cropped[r + 1][c] + cropped[r + 1][c + 1]) // 4 for c in (0, 2)]
        for r in (0, 2)
    ]
    edge_found = any(abs(gray[r][c] - gray[r][c - 1]) > 150 for r in range(6) for c in range(1, 6))
    print("BGR shape:", (6, 6, 3))
    print("Gray shape:", (6, 6))
    print("Cropped shape:", (len(cropped), len(cropped[0])))
    print("Resized pixels:", resized)
    print("Canny edges shape:", (6, 6), "| Edge found:", edge_found)

Verified Console / Dry-Run Output:

BGR shape: (6, 6, 3)
Gray shape: (6, 6)
Cropped shape: (4, 4)
Resized pixels: [[0, 200], [0, 200]]
Canny edges shape: (6, 6) | Edge found: True

5. Essential OpenCV Functions for CBSE Class 10 AI (417) Practicals

OperationOpenCV / NumPy SyntaxCoordinate / Channel RuleCommon Output Shape (from 480Γ—640Γ—3)
Read Color Imagecv2.imread('pic.jpg')Loads in BGR order; returns None if missing(480, 640, 3)
Grayscale Convertcv2.cvtColor(img, cv2.COLOR_BGR2GRAY)Drops 3 color channels to 1 intensity plane(480, 640)
Crop ROIimg[100:300, 50:250]NumPy slicing uses [y1:y2, x1:x2](200, 200, 3)
Resize Imagecv2.resize(img, (320, 240))Tuple order is (width, height)(240, 320, 3)
Canny Edgescv2.Canny(gray, 50, 150)Applies dual hysteresis thresholds(480, 640)
🎯 1-on-1 Live Mentorship & Free Study Kit

Ace Your 50-Mark CBSE AI Practicals with Live Coding

Debug OpenCV scripts, NumPy slicing, and Canny edge pipelines in 1:1 or 1:4 Micro-Pods with 4Achievers Junior.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Passing (height, width) into cv2.resize() instead of (width, height), distorting aspect ratios.
  • Avoid Mistake: Writing img[x1:x2, y1:y2] when cropping instead of row-first img[y1:y2, x1:x2].
  • Avoid Mistake: Forgetting to check if cv2.imread() returned None before calling cv2.cvtColor().
  • Examiner / Mentor Tip: Know why OpenCV uses BGR by default (legacy camera/codec hardware convention) for 50-mark practical viva questions.
  • Examiner / Mentor Tip: Always mention both Canny thresholds (lower discards weak edges; upper confirms strong edges) when explaining edge detection.
  • Examiner / Mentor Tip: Remember that img.shape[:2] gives (height, width), which must be reversed when passed to cv2.resize().

7. Interactive Concept Check Quiz

Question: An image loaded with cv2.imread() has shape (600, 800, 3). Which code correctly crops a 200-pixel tall by 300-pixel wide patch starting at y=100, x=50?

8. Frequently Asked Questions

Why do colors look inverted when displaying cv2.imread() output in Matplotlib?
OpenCV stores channels in BGR order while Matplotlib expects RGB, swapping blue and red unless you convert with cv2.COLOR_BGR2RGB.
Can cv2.Canny() run directly on a color image?
While newer OpenCV versions accept 3-channel inputs, CBSE practical standards convert to grayscale first for cleaner single-intensity gradients.
What happens if you omit cv2.waitKey(0) after cv2.imshow()?
The display window freezes or closes immediately before the user can inspect the image.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class