Atlas Robotics
CameraBasic

OpenCV basics: processing camera images before feeding them to AI

Atlasbot · 18/8/2026 · 11 min read

OpenCV basics: processing camera images before feeding them to AI
Pipeline basic image processing with OpenCV

Before the robot "understands" what it is seeing (object detection, tracking...), the raw frame from the camera typically needs to go through a few basic processing steps — to change the color space, resize, smooth out the noise. OpenCV is the standard library for this, used in nearly every robotic visual pipeline.

Key concepts

OpenCV (Open Source Computer Vision Library) offers hundreds of optimized image processing functions, written in C++ but with full Python binding — most of the robot code uses Python version (cv2) because of its fast writing, easy readability, and speed still good enough because of the heavy computation running in the underlying C++ core.

import cv2

cap = cv2.VideoCapture(0)          # open camera at /dev/video0
ret, frame = cap.read()            # read 1 frame (BGR, not RGB!)

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)   # move to gray image
blurred = cv2.GaussianBlur(gray, (5, 5), 0)      # smoothness, noise reduction
resized = cv2.resize(frame, (640, 480))          # resize AI model

How it works

A confusing point: OpenCV reads images in BGR, not RGB — which is the most common error for novices. cv2.imread/cv2.VideoCapture returns images in color channel order BGR instead of the familiar RGB. If the AI model is trained on an RGB image without conversion, the identification results will be misleading even if the code runs without error.

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # move correctly before putting into model

Technical details

Formulas

Resize the image before introducing the AI model to keep the correct aspect ratio to avoid distortion of the object, which affects the identification accuracy:

Original ratio = Original width / Original height
target ratio = target width / target height

If the original ratio ≠ the target ratio → the image is stretched/distorted on direct resize

VD: original image 640×480 (ratio 4:3), resize straight to 640×640 (ratio 1:1, YOLO requires)
→ circular object in original image distorted to oval after resize

Solution: letterbox — adds padding instead of direct stretching,
keep original ratio inside target frame

Parameters

OperationOpenCV FunctionPurpose
Change Color Spacecv2.cvtColor()BGRRGB, or to HSV for color filtering
Smoothing/Reducing Noisecv2.GaussianBlur()Suppress particle noise before edge/object detection
Resizecv2.resize()Return the required AI model input size
Edge Detectioncv2.Canny()Find object boundaries, used in classical algorithms

Practical applications

OpenCV is a required preprocessing step before embedding images in object detection models such as the YOLO (Computer Vision/AI section) — AI model that expects the right color format (usually RGB), the right fixed input size, and sometimes normalize the pixel value to approximately [0.1]. Skipping any step in this preprocessing sequence keeps the model running (no error message) but gives misleading results — which is the most difficult type of error to diagnose because there is no clear error message.

Practical example

import cv2
import numpy as np

def preprocess_for_model(frame, target_size=640):
    h, w = frame.shape[:2]
    scale = target_size / max(h, w)
    new_w, new_h = int(w * scale), int(h * scale)

    resized = cv2.resize(frame, (new_w, new_h))

    # Letterbox: add padding to preserve the aspect ratio
    canvas = np.full((target_size, target_size, 3), 114, dtype=np.uint8)
    pad_x, pad_y = (target_size - new_w) // 2, (target_size - new_h) // 2
    canvas[pad_y:pad_y+new_h, pad_x:pad_x+new_w] = resized

    rgb = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
    normalized = rgb.astype(np.float32) / 255.0
    return normalized

frame = cv2.imread("test.jpg")
processed = preprocess_for_model(frame)
print(f"Kich thuoc dau vao mo hinh: {processed.shape}, gia tri: [{processed.min():.2f}, {processed.max():.2f}]")
Output:
Kich thuoc dau vao mo hinh: (640, 640, 3), gia tri: [0.00, 1.00]

This pipeline illustrates the four most important preprocessing steps: resize keep ratio (letterbox), color change BGR →RGB, and pixel value normalization — which lack any steps that could cause the AI model to give wrong results without error reporting.

Common mistakes

  • BGR is erroneously switched to RGB prior to the inclusion of the AI— model as stated in Operation Principles section, this is the most common error, the model still runs but the erroneous results have no warning.
  • Direct resize does not keep the frame ratio— as calculated in the Formulation section, causing object distortion, affecting recognition accuracy, especially for objects with characteristic shapes (signals, barcodes).
  • Expense with the pixel value normalization step when the model requires— multiple AI models expected input in the range [0.1] or normalized to specific mean/std, straight-forwarding the original pixel value [0.255] causing the model to erroneously behave.
  • Does not check that the output image size matches the input requirements of the—model can automatically resize (some frameworks), but not always, requiring explicit confirmation.

Conclusion

OpenCV is an image processing platform that most robotic visual pipelines pass through before the AI — step. Mastery of the basic operations (color change, resize keep ratio, normalization) and the memorization of the BGR/RGB task will largely avoid the "model run but wrong result" error at the start. The next article in the column goes into image_transport— how to efficiently send images between ROS2 nodes when the system has multiple computers.

Get new articles and lessons by email

When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.

Unsubscribe any time with the link in each email. See our Privacy policy.

OpenCV basics: processing camera images before feeding them to AI — Atlas Robotics