Computer Vision

Updated · 8 min read
mediumPython 3.13aicomputer-visionimagesimage-classificationobject-detection

Computer vision is the part of AI that lets computers understand images and video: what is in a picture, where each thing is, and what is happening. It recognizes your face to open your phone, reads the numbers on a check, spots tumors in scans, and helps cars stay in their lane.

To a computer, an image is a grid of numbers. A vision model learns to turn those numbers into answers, and the most important kind of model for images is the convolutional neural network (CNN), covered in the next lesson.

What Computer Vision Does

TaskDescription
Image classificationIt is used to give the whole image one label: "golden retriever", "receipt", "pneumonia"
Object detectionIt is used to find each object and draw a box around it, with a label
SegmentationIt is used to label every pixel: which pixels are road, car, person or sky
Text recognition (OCR)It is used to read printed or handwritten text in an image
Face recognitionIt is used to match a face against known people; it raises serious privacy questions
Image generationIt is used to create new images from text; see "Text, Image, Audio and Video Generation"

Example: A Photo Is a Grid of Numbers

The programs in this chapter need pip install torch transformers pillow scipy scikit-learn. The first run downloads each pretrained model from Hugging Face; the download and loading messages are left out of the output shown.

This program opens a photo and looks at its numbers. It uses a public domain photo of a golden retriever (File:Golden-retriever-dog.jpg on Wikimedia Commons, CC0), saved as dog.jpg. Any photo works.

Python
import numpy as np
from PIL import Image
 
photo = Image.open("dog.jpg")                  # any JPEG or PNG photo
print("Size:", photo.size, "| mode:", photo.mode)
 
pixels = np.array(photo)                       # the photo as a grid of numbers
print("Array shape:", pixels.shape, "| type:", pixels.dtype)
print("Top-left pixel (red, green, blue):", pixels[0, 0])
print("Center pixel (red, green, blue):", pixels[360, 480])
print("Numbers in this photo:", f"{pixels.size:,}")
 
gray = np.array(photo.convert("L"))            # one brightness number per pixel
print("Grayscale shape:", gray.shape, "| darkest", gray.min(), "| brightest", gray.max())
 
small = np.array(photo.resize((224, 224)))     # the size most image models expect
print("Resized for a model:", small.shape)
Output
Size: (960, 720) | mode: RGB
Array shape: (720, 960, 3) | type: uint8
Top-left pixel (red, green, blue): [10 12  9]
Center pixel (red, green, blue): [174 148  99]
Numbers in this photo: 2,073,600
Grayscale shape: (720, 960) | darkest 0 | brightest 255
Resized for a model: (224, 224, 3)

Explanation:

  • The photo is 960 pixels wide and 720 tall. NumPy stores it as an array of shape (720, 960, 3): 720 rows, 960 columns, and 3 color channels, red, green and blue.
  • Each number is from 0 to 255 (uint8). The top-left pixel [10 12 9] is nearly black; the center pixel [174 148 99] is the dog's golden fur.
  • 2,073,600 numbers describe this one photo. Grayscale keeps one brightness number per pixel instead of three.
  • Most image models expect a fixed size, often 224 × 224, so photos are resized first.

Example: Classifying a Photo with a Pretrained Model

A pretrained model has already been trained by someone else, usually on millions of images. ResNet-18 is a CNN trained on ImageNet, 1.28 million photos labeled with 1,000 classes, from "goldfish" to "school bus".

A photo is 2 million numbers; a pretrained CNN turns them into an answer
Python
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification
 
# ResNet-18: a convolutional network trained on 1.28 million ImageNet photos in 1,000 classes
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-18")
model = AutoModelForImageClassification.from_pretrained("microsoft/resnet-18")
model.eval()
 
photo = Image.open("dog.jpg")
inputs = processor(images=photo, return_tensors="pt")   # resize, crop, scale the pixels
print("Model input shape:", tuple(inputs["pixel_values"].shape))
 
with torch.no_grad():
    scores = model(**inputs).logits                      # one score per class
probs = scores.softmax(dim=1)[0]
print("Classes:", len(probs))
 
top = probs.topk(3)
for p, i in zip(top.values, top.indices):
    print(f"{p:6.1%}  {model.config.id2label[i.item()]}")
Output
Model input shape: (1, 3, 224, 224)
Classes: 1000
 98.4%  golden retriever
  0.4%  Labrador retriever
  0.2%  Great Pyrenees

Explanation:

  • AutoImageProcessor prepares the photo exactly the way ResNet-18 was trained: it resizes and crops to 224 × 224 and scales the pixel values. The input shape (1, 3, 224, 224) means one image, 3 channels, 224 × 224 pixels. PyTorch puts the channels first.
  • The model gives 1,000 scores, one per class, and softmax turns them into probabilities that add up to 1.
  • Golden retriever, 98.4%. The next guesses are other large, light-colored dogs, which shows the model learned what dogs look like, not just one label.
  • Nothing was trained here. The model was downloaded once (about 45 MB) and used as is.

Classification, Detection and Segmentation

ClassificationObject detectionSegmentation
Answers"What is in this image?""What is where?""Which pixels belong to what?"
OutputOne label and a probabilityA box, label and score for each objectA label for every pixel
Example useSorting photos, checking X-raysCounting cars, self-checkout, wildlife camerasSelf-driving cars, medical scans, photo background removal
Well-known modelsResNet, EfficientNet, Vision Transformer (ViT)YOLO, Faster R-CNN, DETRU-Net, Mask R-CNN, Segment Anything (SAM)

Vision Transformers use the same attention idea as large language models, applied to small patches of an image instead of words. Today they compete with CNNs on many tasks, and multimodal models combine vision with language, so you can ask a question about a photo in plain English. See "Foundation Models and Multimodal AI".

Common Mistakes

Forgetting the preprocessing. A model gives poor answers on images that are not resized and scaled the way it was trained. Use the model's own processor.

Mixing up the shape order. NumPy and Pillow give height × width × channels; PyTorch models want channels × height × width, with a batch dimension in front.

Trusting a confident label outside the model's classes. A classifier always picks one of its classes, even for a photo that fits none of them.

Ignoring bias and privacy. Face recognition and similar systems can work worse for some groups of people and can track people without consent. See "AI Bias in Everyday Tools".

Interview Corner

How does a computer represent a color image?

As an array of numbers with shape height × width × 3, one value from 0 to 255 for each of red, green and blue at every pixel. A 960 × 720 photo is 2,073,600 numbers.

What is the difference between classification, detection and segmentation?

Classification gives one label for the whole image, detection finds each object with a box and a label, and segmentation labels every pixel. Each gives more detail than the one before and needs more detailed training labels.

Practice

Exercise: classify your own photos. Run the classifier on three photos of your own: one of a common object, one of a pet or food, and one of a document. Which ones does it label well, and what does it say about the document?

Check your understanding:

  1. What does the shape (720, 960, 3) mean?
  2. Why is the photo resized to 224 × 224 before classification?
  3. Which task would you use to count the cars in a parking lot photo?

Quick check: computer vision

4 questions
1How many numbers describe a 960 × 720 color photo?
2What did ResNet-18 say about the dog photo?
3Which task labels every pixel?
4What did the pretrained model need before it could classify the dog?

Key Takeaways

Quick reference

NeedCode
Open a photoImage.open("dog.jpg")
Photo to numbersnp.array(photo)
Grayscale or resizephoto.convert("L"), photo.resize((224, 224))
Pretrained classifierAutoModelForImageClassification.from_pretrained("microsoft/resnet-18")
Prepare the imageAutoImageProcessor.from_pretrained(...)(images=photo, return_tensors="pt")
Top 3 classeslogits.softmax(dim=1)[0].topk(3)

Was this tutorial helpful?

Lesson 140 of 186