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 pixels. If stored as three 8-bit unsigned channels per pixel without compression, its pixel data requires:
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 inNCHWorder (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:
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.
2. Major computer vision tasks
A useful way to understand computer vision is to distinguish what the system must output.
| Task | Output | Example |
|---|---|---|
| Image classification | One or more labels for an image | Identifying whether a radiograph contains a particular pattern |
| Object detection | Object labels and approximate bounding boxes | Locating vehicles in a traffic image |
| Semantic segmentation | A class label for each pixel | Identifying road, sidewalk, and vegetation regions |
| Instance segmentation | Separate masks for individual object instances | Distinguishing three overlapping people |
| Optical character recognition (OCR) | Text extracted from visual input | Reading an invoice or street sign |
| Keypoint or pose estimation | Locations of meaningful points | Estimating human joint positions |
| Object tracking | Identities or trajectories over frames | Following a ball through video |
| Depth estimation | Estimated scene distance or geometry | Supporting obstacle avoidance |
| Image retrieval | Ranked visually related images | Finding 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.
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:
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
| Approach | How representation is obtained | Strength | Limitation |
|---|---|---|---|
| Thresholding and morphology | Rules on intensity and spatial structure | Simple, explainable, efficient in controlled settings | Sensitive to changing light and scene conditions |
| Edge/corner descriptors | Designed algorithms measure local patterns | Useful for geometric matching and registration | May struggle with large appearance variations |
| Classical machine learning | Extract features first, then train a classifier | Practical with limited structured features | Feature design can constrain performance |
| Deep learning | Learns representations and predictions from data | Strong adaptability on complex visual tasks | Often 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
| Task | Common evaluation approach | Important caution |
|---|---|---|
| Classification | Accuracy, precision, recall, F1-score, confusion matrix | Accuracy can conceal poor performance on rare classes. |
| Detection | Intersection over Union (IoU), average precision (AP), mean AP (mAP) | Results depend on overlap thresholds and the benchmark’s averaging protocol. |
| Segmentation | Pixel-level IoU, Dice coefficient | Large background regions can dominate naive pixel accuracy. |
| OCR | Character error rate (CER), word error rate (WER) | Results depend on transcription and normalization conventions. |
| Tracking | Identity consistency and association metrics | Correct detections can still be linked to the wrong objects. |
For a predicted bounding box and a ground-truth box , Intersection over Union measures overlap:
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:
- Vectors and Matrices explain the numerical arrays underlying images and transformations.
- NumPy, Arrays, and Tensors introduce shape, indexing, and numerical representation.
- Convolutional and Recurrent Neural Networks introduce convolutional architectures and sequence models.
- Deep Learning with PyTorch covers training and evaluating neural networks.
- Data Splitting, Labeling, and Leakage addresses dataset design and leakage prevention.
- Evaluating Machine Learning Models establishes general evaluation principles.
Continue with these planned topics:
- Image Classification, Detection, and Segmentation for the main visual prediction tasks in depth.
- Speech and Audio AI for a different sensory modality.
- The Transformer Architecture for the attention-based architecture also used in modern visual models.
- Multimodal Artificial Intelligence for systems combining images with text, audio, or other signals.
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
- Szeliski, Computer Vision: Algorithms and Applications, 2nd edition — broad treatment of image formation, features, geometry, recognition, and applications.
- Stanford CS231n: Deep Learning for Computer Vision — visual recognition and deep learning foundations.
- PyTorch Tutorials — practical tensor operations and vision-model workflows.
- scikit-image documentation — classical image processing and computer vision methods.
- OpenCV documentation — image processing, computer vision algorithms, and video analysis.
- COCO dataset and evaluation resources — widely used object detection and segmentation benchmark resources.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.