Artificial Intelligence • AI Application Domains • 16 min read

Computer Vision Fundamentals

Start with an example: What a computer sees in a photograph

Imagine showing a computer a photograph of a bicycle. You see a familiar object immediately. The program initially receives a grid of numerical pixel values: positions and color or intensity measurements. Those numbers alone do not arrive with labels such as “wheel” or “handlebar.”

A vision pipeline turns the image into a useful output. It might classify the whole photo, place a box around the bicycle, or identify which pixels belong to it. The task determines what kind of answer is needed.

Computer vision is the field that develops these methods. Some controlled tasks need only basic image-processing rules, while more complex tasks use trained models such as convolutional neural networks and Vision Transformers. The right method depends on the problem, the data, and the cost of being wrong.

Computer vision is the field of artificial intelligence concerned with developing computational methods that extract information from images and videos. A vision system might identify objects, locate defects, read text, measure motion, or distinguish regions of a scene. The output depends on the task: a label, a set of coordinates, a pixel mask, extracted text, or a numerical estimate.

Computer vision is an application domain, not a single neural network architecture. It includes classical image-processing methods, geometry, statistical approaches, traditional machine learning, and deep learning. A rule-based threshold may be sufficient to count bright objects in a controlled image, while identifying many objects in complex scenes may require a trained model.

1. How computers represent images

A digital image is a discrete grid of pixels. Each pixel stores one or more numerical values describing recorded intensity or color. Pixel values do not directly mean “cat,” “road,” or “tumor.” A vision system must infer meaningful structures from the values and their spatial relationships.

Image dimensions and channels

The shape of an image is commonly described by its height, width, and number of channels:

  • A grayscale image has one intensity channel and often has array shape (height, width).
  • An RGB image has red, green, and blue channels and often has shape (height, width, 3).
  • An RGBA image adds an alpha channel, usually used for transparency. Alpha is not another ordinary color channel.
  • A video is a time-ordered sequence of frames, potentially accompanied by audio and timestamps.

For example, an RGB image measuring 640 pixels wide and 480 pixels high contains 640×480=307,200640 \times 480 = 307{,}200 pixels. If stored as three 8-bit unsigned channels per pixel without compression, its pixel data requires:

307,200×3=921,600 bytes.307{,}200 \times 3 = 921{,}600\ \text{bytes}.

Actual image files may be substantially smaller or larger depending on compression, metadata, bit depth, and file format.

Note: Tensor layout depends on the library. NumPy images commonly use HWC (height, width, channels). PyTorch convolutional layers generally expect batches in NCHW order (batch, channels, height, width).

Resolution, intensity, and color

Spatial resolution describes how many pixels represent a scene, but high pixel counts alone do not guarantee high-quality visual information. Focus, illumination, motion blur, sensor noise, compression, and the size of the subject also matter.

An 8-bit grayscale image typically stores values from 0 (dark) to 255 (bright). A color image commonly records three values at each location. These values depend on the color representation and image acquisition pipeline; the same numerical triplet does not necessarily have the same physical meaning across every color space.

A tiny image as a matrix

A grayscale image can be represented as a matrix:

I=[202024024020202402402020240240].I = \begin{bmatrix} 20 & 20 & 240 & 240 \\ 20 & 20 & 240 & 240 \\ 20 & 20 & 240 & 240 \end{bmatrix}.

The left side is dark and the right side is bright. A large intensity change between adjacent columns suggests a vertical edge. This illustrates a foundational idea: useful visual structure can be inferred from patterns across neighboring pixels, not just individual pixel values.

A grayscale pixel grid with dark pixels on the left and bright pixels on the right, showing an edge between them
Edges arise where neighboring pixel values change substantially. Real edge detectors also account for direction, noise, and local context.

2. Major computer vision tasks

A useful way to understand computer vision is to distinguish what the system must output.

TaskOutputExample
Image classificationOne or more labels for an imageIdentifying whether a radiograph contains a particular pattern
Object detectionObject labels and approximate bounding boxesLocating vehicles in a traffic image
Semantic segmentationA class label for each pixelIdentifying road, sidewalk, and vegetation regions
Instance segmentationSeparate masks for individual object instancesDistinguishing three overlapping people
Optical character recognition (OCR)Text extracted from visual inputReading an invoice or street sign
Keypoint or pose estimationLocations of meaningful pointsEstimating human joint positions
Object trackingIdentities or trajectories over framesFollowing a ball through video
Depth estimationEstimated scene distance or geometrySupporting obstacle avoidance
Image retrievalRanked visually related imagesFinding products with a similar appearance

These tasks can be composed. For example, a document system may first locate a page, correct its orientation, detect text regions, run OCR, and then send the extracted text to a natural language processing system.

Classification versus detection: A classifier says what is present in an image, but it does not necessarily say where. A detector provides locations, often as rectangles. Detection versus segmentation: A bounding box approximates an object’s region; a segmentation mask assigns labels at the pixel level. The next article examines these tasks in greater depth.

3. The basic vision-system workflow

A typical system has a development workflow and an inference workflow. During development, engineers collect representative images, annotate examples when needed, select or train models, and evaluate performance. During inference, a deployed system receives new images and produces outputs using fixed learned parameters, unless explicitly updated.

Computer vision workflow: capture images, preprocess, extract representations, predict, and evaluate outputs
Vision systems convert raw visual measurements into representations and task-specific outputs.

Step 1: Capture or obtain the image

Images may originate from cameras, scanners, microscopes, satellites, or existing datasets. Their characteristics matter: camera angle, lighting, resolution, file encoding, and whether the dataset represents the conditions where the model will be used.

Step 2: Preprocess the input

Common preprocessing operations include:

  • Resizing: changing image dimensions to match model requirements; some methods also preserve aspect ratio with padding.
  • Cropping: selecting an image region, while ensuring that important objects are not accidentally removed.
  • Normalization: mapping pixel values to an expected numerical scale, sometimes with channel-specific mean and standard deviation.
  • Color conversion: for example, RGB to grayscale when color is not required.
  • Denoising: suppressing sensor or compression noise without erasing useful details.
  • Geometric corrections: rotating, rectifying, or aligning images when necessary.

The exact preprocessing used during inference must match what the model expects from training. Changing channel order or normalization can substantially degrade predictions.

Step 3: Extract useful representations

Classical computer vision can use explicitly designed measurements, such as edges, corners, textures, color histograms, and geometric shapes. Deep learning usually learns visual features from training data. Early layers may respond to local patterns, while deeper layers learn task-relevant combinations of features; these patterns are not guaranteed to correspond to neat human concepts.

Step 4: Produce and interpret predictions

The final stage may output class scores, boxes, masks, text, or other measurements. An application may apply a confidence threshold, remove duplicate detections, or request human review before taking an action. A high model score should not automatically be interpreted as a well-calibrated real-world probability.

4. Traditional image processing and learned models

Image processing transforms or analyzes images through computational operations. Not every image-processing operation is AI: sharpening, cropping, and changing brightness are ordinary signal-processing tasks. Computer vision uses image-processing techniques but goes further by extracting information about the visual scene.

Filtering and edges

A convolution combines local image values using a small matrix called a kernel. A smoothing kernel averages nearby values; an edge-detection kernel responds to rapid intensity changes. In discrete two-dimensional form, convolution is often expressed as:

(I∗K)[i,j]=∑m∑nI[i−m,j−n]K[m,n].(I * K)[i,j] = \sum_m \sum_n I[i-m,j-n]K[m,n].

Some software functions named convolution actually calculate cross-correlation (without reversing the kernel). Both apply local weighted operations; be careful about the mathematical convention used by a library.

Handcrafted features versus learned features

ApproachHow representation is obtainedStrengthLimitation
Thresholding and morphologyRules on intensity and spatial structureSimple, explainable, efficient in controlled settingsSensitive to changing light and scene conditions
Edge/corner descriptorsDesigned algorithms measure local patternsUseful for geometric matching and registrationMay struggle with large appearance variations
Classical machine learningExtract features first, then train a classifierPractical with limited structured featuresFeature design can constrain performance
Deep learningLearns representations and predictions from dataStrong adaptability on complex visual tasksOften needs substantial data, computation, and careful evaluation

A production application may combine these techniques. An industrial inspection pipeline, for example, could use geometric alignment before feeding a cropped region to a trained defect classifier.

5. Neural networks used for visual data

Convolutional neural networks (CNNs)

A convolutional neural network uses learnable local filters to produce feature maps. Weight sharing allows the same filter to operate across multiple image locations. CNNs are well suited to local spatial patterns, though their exact ability to model long-range relationships depends on architecture and depth.

Typical CNN components include convolutional layers, nonlinear activation functions, downsampling or pooling operations, and a task-specific prediction head. A classification CNN may reduce spatial feature maps and produce class scores. Detection or segmentation systems require architectures that also preserve or reconstruct spatial information.

Vision Transformers (ViTs)

A Vision Transformer commonly divides an image into patches, maps those patches into token-like vectors, and processes their relationships using attention mechanisms. Variants differ in how they build visual representations and manage computational cost. ViTs are not automatically better than CNNs in every dataset, device, or latency setting.

Transfer learning

Training a large visual model from scratch can be expensive. Transfer learning starts from a model pretrained on another dataset and adapts it to a new task. Engineers may train a new output layer, fine-tune some existing layers, or update the whole network. When the original dataset and target setting differ substantially, adaptation and careful evaluation are especially important.

6. Practical example: inspect and preprocess an image with Python

The following example generates a tiny RGB image directly as a NumPy array, then shows the operations needed to prepare image values for a PyTorch model. It avoids any external image file so the example can be reproduced as written.

import numpy as np
import torch

# Three rows, four columns, three color channels (RGB).
image = np.array(
    [
        [[255, 0, 0], [255, 0, 0], [0, 255, 0], [0, 255, 0]],
        [[255, 0, 0], [255, 0, 0], [0, 255, 0], [0, 255, 0]],
        [[0, 0, 255], [0, 0, 255], [255, 255, 255], [255, 255, 255]],
    ],
    dtype=np.uint8,
)

print("NumPy image shape:", image.shape)  # (3, 4, 3)
print("Pixel at top left:", image[0, 0])  # [255   0   0]

# Convert pixel values from 0..255 to floating point in 0..1.
scaled = image.astype(np.float32) / 255.0

# PyTorch vision models typically expect NCHW tensor order.
tensor = torch.from_numpy(scaled).permute(2, 0, 1).unsqueeze(0)

print("PyTorch batch shape:", tuple(tensor.shape))  # (1, 3, 3, 4)
print("Value range:", tensor.min().item(), tensor.max().item())

The resulting tensor has one sample, three channels, three rows, and four columns. This is input preparation, not a trained classifier. The normalization and image-size requirements of any actual pretrained model must be followed exactly; many require additional mean/standard-deviation normalization and a specific input resolution.

To use the example in a new project, install compatible versions of NumPy and PyTorch in a Python environment. The code does not assume a GPU.

7. Building and evaluating a vision dataset

Image quality is only part of dataset quality. Good model evaluation also requires trustworthy labels, meaningful splits, and coverage of real operating conditions.

Labeling

The annotation format depends on the task:

  • Classification: one or more labels per image.
  • Detection: class labels and bounding boxes, with an agreed coordinate convention.
  • Segmentation: pixel-level masks and a clearly defined class taxonomy.
  • OCR: text transcriptions, sometimes with word or line locations.

Annotation instructions should address ambiguous cases, partially visible objects, and whether background or uncertain regions are labeled. Annotation disagreements can reveal unclear task definitions.

Data splitting and leakage

Divide data into training, validation, and test sets according to the intended generalization problem. Randomly splitting individual images is not always sufficient. Frames from the same video, photographs from the same person, or repeated images of the same physical item can make evaluation unrealistically optimistic if near-duplicates appear across splits.

Depending on the application, splitting by person, camera, location, session, device, or time may better simulate deployment. Preprocessing transformations learned from data must be fitted on training data alone.

Data augmentation

Augmentation creates variations of training examples, such as crops, rotations, color adjustments, or small geometric changes. The transformations must preserve the correct label. Horizontal flips may be reasonable for some object-recognition tasks but inappropriate for reading text or distinguishing left from right in a medical context.

Evaluation metrics

TaskCommon evaluation approachImportant caution
ClassificationAccuracy, precision, recall, F1-score, confusion matrixAccuracy can conceal poor performance on rare classes.
DetectionIntersection over Union (IoU), average precision (AP), mean AP (mAP)Results depend on overlap thresholds and the benchmark’s averaging protocol.
SegmentationPixel-level IoU, Dice coefficientLarge background regions can dominate naive pixel accuracy.
OCRCharacter error rate (CER), word error rate (WER)Results depend on transcription and normalization conventions.
TrackingIdentity consistency and association metricsCorrect detections can still be linked to the wrong objects.

For a predicted bounding box BpB_p and a ground-truth box BgB_g, Intersection over Union measures overlap:

IoU⁡(Bp,Bg)=∣Bp∩Bg∣∣Bp∪Bg∣.\operatorname{IoU}(B_p,B_g) = \frac{|B_p \cap B_g|}{|B_p \cup B_g|}.

IoU equals 1 for identical boxes and 0 when boxes do not overlap. It says nothing by itself about whether the predicted object class is correct. Detection evaluation usually combines localization and classification requirements.

8. Where computer vision is used

Computer vision is useful when an application needs consistent, scalable analysis of visual information:

  • Manufacturing: inspect parts for visible defects and count items on production lines.
  • Healthcare: assist with interpreting medical images, subject to clinical validation and appropriate oversight.
  • Agriculture: estimate crop conditions from field images and aerial imagery.
  • Transportation: detect roads, vehicles, pedestrians, or hazards for driver-assistance and robotics systems.
  • Documents: locate page regions, recognize printed text, and extract structured document contents.
  • Accessibility: describe or identify visual information, while communicating uncertainty.
  • Science: analyze microscope images, satellite scenes, or experimental video.

The right engineering approach depends on the cost of mistakes. A missed defect, a wrong medical interpretation, and an incorrect photo tag do not have equivalent consequences.

9. Limitations and engineering considerations

Distribution shift. A model trained on bright daytime images may perform poorly at night. New camera hardware, weather, geography, and background conditions can also change inputs.

Occlusion and scale. Objects may be partially hidden, tiny, blurred, or far from the camera. Vision systems do not automatically reconstruct information that the sensor never captured.

Spurious correlations. Models may use backgrounds, watermarks, or capture artifacts that correlate with labels instead of learning the intended visual concept.

Bias and representativeness. Inadequate coverage across people, environments, and image conditions can lead to unequal performance. Claims of fairness must be supported by task-relevant evaluation, not assumed from average accuracy.

Robustness and security. Image manipulation, adversarial patterns, corrupted inputs, and sensor failures can affect predictions. High-stakes systems need fail-safe behavior and monitoring.

Privacy. Capturing faces, license plates, documents, or other identifiable information can create privacy and legal obligations. Data collection and retention should be proportional to the intended purpose.

Resources and latency. Real-time vision may have strict computation, memory, power, and response-time constraints. A small optimized model may be preferable to a larger model on a mobile or embedded device.

Interpretation. A confidence score is not proof of correctness, and a visually plausible heatmap is not necessarily a faithful causal explanation of the model’s decision.

10. How computer vision connects to other AI topics

Computer vision depends on foundations already covered in the PlainCS knowledge map:

Continue with these planned topics:

The connection to AI engineering is direct: a useful vision product needs more than accurate predictions. It also needs reliable input capture, preprocessing, deployment, monitoring, privacy protection, and appropriate handling of uncertain outputs.

References and further reading

Related articles in

Image preview

Fit