Detailed content
🧭 The map of vision tasks
Computer vision is the field that enables programs to extract information from images and videos. To a computer, a photo is a grid of pixels —each with three color values (red, green, blue). The model’s job is to turn this grid into a useful answer. The type of answer defines the task, and choosing the right task is half the project.
A classification answers “what’s in the image?” with a label. detection answers “what and where?” with boxes. segmentation answers “which pixels belong to what?” with masks. OCR reads text. And VLMs (vision-language models, vision-language models) answer natural-language questions about the image. The more detailed the output, the more it costs to label the data and run the model.
What it is
This is how vision tasks are classified by output type: label (classification), boxes (detection), masks (segmentation), text (OCR), and free-form answer or JSON (VLM). Each has its own models, annotation formats, and metrics.
| Task | Output | Example use |
|---|---|---|
| Classification | Label + confidence | Good or defective part. |
| Detection | Boxes with classes | Count products on a shelf. |
| Segmentation | Pixel-level mask | Measure rust area, remove background. |
| Pose | Body points (keypoints) | Exercise posture, ergonomics. |
| OCR | Text + position | Read invoices and license plates. |
| VLM | Free text or JSON | Describe, answer, extract fields. |
Why learn
Vision projects often fail because they choose the wrong task: segmenting when boxes would do, or using a slow VLM when a small detector can run in real time. The map helps you size the data, hardware, and timeline before writing code.
Key concepts
📦 Detection with YOLO
O YOLO (You Only Look Once, first released in 2015) is the most widely used family of detectors in practice: it looks at the image once and returns all the boxes with their class and confidence (a number from 0 to 1 that indicates how certain the model is about that detection). The ultralytics library packages several generations of YOLO behind the same interface in Python and on the command line; pretrained models recognize the 80 classes in the COCO dataset (person, car, dog, bottle…).
Two concepts explain almost every detector adjustment. IoU (Intersection over Union) measures how much two boxes overlap: the area of the intersection divided by the area of the union, from 0 to 1. NMS (Non-Maximum Suppression) uses IoU to remove duplicates: when several boxes cover the same object, the one with the highest confidence is kept and boxes with too much overlap are discarded. The two settings you adjust most often are the confidence threshold (conf) and the NMS IoU threshold (iou).
What it is
Object detection means locating each object with a box (coordinates x1, y1, x2, y2), a class, and a confidence score. YOLO does this in real time on a GPU and at acceptable speeds on a CPU with its smaller versions.
Try this: detect and count objects in an image, locally.
# detectar.py — install: pip install ultralytics
# usage: python3 detectar.py <foto.jpg ou URL>
import sys
from collections import Counter
from ultralytics import YOLO
imagem = sys.argv[1] if len(sys.argv) > 1 else "https://ultralytics.com/images/bus.jpg"
modelo = YOLO("yolo11n.pt") # "nano" version; downloads the weights the first time
resultado = modelo(imagem, conf=0.25, iou=0.7)[0]
contagem = Counter()
for caixa in resultado.boxes:
classe = resultado.names[int(caixa.cls)]
conf = float(caixa.conf)
x1, y1, x2, y2 = [round(v) for v in caixa.xyxy[0].tolist()]
contagem[classe] += 1
print(f"{classe:12s} conf={conf:.2f} caixa=({x1},{y1})-({x2},{y2})")
print("\nCONTAGEM:", dict(contagem))
resultado.save(filename="detectado.jpg") # image with boxes drawn
print("imagem salva em detectado.jpg")
How to check: with the sample image (a bus on the street), the count should include bus and a few person. Open detectado.jpg and check whether the boxes match the objects. Run it again with conf=0.6: fewer boxes appear, and the ones that disappear have lower confidence.
💡 Tip
The YOLO family gets new versions frequently, and ultralytics usually keeps the same interface. Replace yolo11n.pt with the name of a newer version from the documentation and compare it in your own test. The suffix indicates the size: n (nano) and s run on a CPU; m, l e x require a GPU. Also check the ultralytics license (AGPL) before embedding it in a closed-source product.
Why learn
Detection is the vision task with the most direct applications: counting, inventory, workplace safety, and quality control. Understanding confidence, IoU, and NMS lets you adapt a ready-made detector to your situation without training anything.
Key concepts
🧩 Segmentation
When a box is too rough, use segmentation: each pixel gets a label. In semantic segmentation, all "person" pixels get the same color, without distinguishing individuals. In instance segmentation, each person gets their own mask. The panoptic segmentation combines the two: separately identified countable objects and the background (sky, street) labeled by class.
An important shift came with Segment Anything (SAM), from Meta, in 2023, and SAM 2 in 2024, which extends the idea to video. These are promptablemodels: you click a point or draw a box, and the model returns a mask for the object, even for classes it has never seen during training. In practice, a common workflow is to detect objects with YOLO and pass the boxes to SAM for precise cutouts—or use an instance segmentation model such as yolo11n-seg.pt, which returns a box and a mask at once.
What it is
Segmentation classifies every pixel in an image. The output is a mask (an image of the same size in which each pixel indicates which object or class it belongs to), useful when an object's shape and area matter.
Semantic
One color per class. Good for measuring area: how much of a field is dry, or how much of a wall has water damage.
Instance
One mask per object. Good for counting and measuring each item: fruit on a conveyor belt, cells on a slide.
Promptable (SAM)
A mask from a click or box. Good for annotating data quickly and for on-demand cutouts.
✓ Use segmentation
- ✓The answer depends on area, outline, or shape.
- ✓Touching or overlapping objects that boxes merge together.
- ✓Background removal for product catalogs.
✗ A box is enough
- ✗You only need to count or determine whether something is present.
- ✗Short annotation budget: masks cost more to label.
- ✗Limited edge hardware and real-time requirements.
Why learn
Segmentation enables measurements that detection can’t provide—area, outline, and clean cropping—and promptable models have greatly reduced the work of annotating data. Knowing when to use it helps you avoid paying the cost of a mask when you don’t need one.
Key concepts
🔤 OCR and documents
OCR (Optical Character Recognition) turns an image of text into actual text that you can copy, search, and process. Classic OCR works in two steps: detect where text appears and recognize the characters in each segment. Open tools such as Tesseract, PaddleOCR, and docTR do this locally and work well on clean scanned documents.
The real problem is almost never reading the letters; it's understanding the layout — what the total number is, which row belongs to which table column, what a header is. That’s why two approaches have grown: models specialized in document layout and VLMs, which receive the image and return the requested fields directly in JSON. VLMs are more flexible; classic OCR is more predictable, faster, and tells you exactly where each word is.
What it is
OCR converts an image of text into text. Document extraction goes further: it identifies fields (date, CNPJ, total amount) and structure (tables, sections), combining OCR, layout analysis, and increasingly, VLMs.
| Approach | Good at | Watch out for |
|---|---|---|
| Classic OCR (Tesseract) | Clean printed text; runs on any machine. | Skewed photos, handwriting, complex tables. |
| Deep learning OCR (PaddleOCR, docTR) | Phone photos, varied fonts, word positions. | Still needs rules to assemble the fields. |
| VLM (qwen2.5vl, llava, commercial models) | Extracting fields directly into JSON, understanding context. | May make up an illegible value; slower. |
💡 Tip
For documents that affect money or decisions (invoices, payment slips, medical reports), validate the extracted data with rules: CNPJ check digit, item sum equal to the total, date within a plausible range. When a rule fails, send it for human review instead of trusting the reading.
Why learn
Much of the information companies use still lives in scanned PDFs, photos, and paper documents. Automating reading with validation is one of the vision projects with the quickest payoff—and one that requires the most care to catch silent errors.
Key concepts
🗣️ Vision-language models
A VLM combines an image encoder (a model that turns the photo into vectors) with a language model. The image is cut into pieces (patches), each piece becomes a vector, and those vectors enter the LLM as if they were tokens, alongside your text. The LLM then responds about everything together. That’s how ChatGPT, Claude, and Gemini “see” images—and so do open models that run on Ollama, such as llava e qwen2.5vl.
The most useful application in systems isn’t conversation: it’s structured extraction. You send the image with a request for JSON output (defined fields, null values when something can’t be seen) and treat the response as data. Through Ollama’s OpenAI-compatible route, the image is sent as image_url with the file encoded in base64—the same format used by paid APIs.
What it is
A vision-language model receives image and text in the same input and generates text. It can describe, answer questions, compare images, and extract information in a structured format, without training a model for each task.
Try this: extract fields from a photo of a receipt or invoice with a local VLM.
# extrair_imagem.py — local VLM in Ollama through the /v1 route
# setup: ollama pull qwen2.5vl:7b (or: ollama pull llava)
# pip install openai
# usage: python3 extrair_imagem.py <foto_do_cupom.jpg>
import base64, json, mimetypes, sys
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # Paid API: replace the URL and key
MODEL = "qwen2.5vl:7b"
path = sys.argv[1]
image_type = mimetypes.guess_type(path)[0] or "image/jpeg"
b64 = base64.b64encode(open(path, "rb").read()).decode()
request = """Extract the data from this image and respond ONLY with JSON:
{"estabelecimento": str|null, "data": "AAAA-MM-DD"|null,
"total": number|null, "itens": [{"descricao": str, "valor": number}]}
If a field is illegible, use null. Do not make up values."""
resp = client.chat.completions.create(
model=MODEL,
temperature=0,
response_format={"type": "json_object"},
messages=[{"role": "user", "content": [
{"type": "text", "text": request},
{"type": "image_url", "image_url": {"url": f"data:{image_type};base64,{b64}"}},
]}],
)
data = json.loads(resp.choices[0].message.content)
print(json.dumps(data, ensure_ascii=False, indent=2))
item_sum = round(sum(i.get("valor") or 0 for i in data.get("itens", [])), 2)
if data.get("total") is not None and abs(item_sum - data["total"]) > 0.01:
print(f"WARNING: item sum ({item_sum}) differs from the total — review manually")
How to check: photograph a real receipt and run the script. The JSON should parse without errors, and the fields should match the paper. Cover the total with your finger and take another photo: the total must be null. If a number appears, the model made it up—and the sum check at the end exists precisely to catch this kind of error.
Why learn
VLMs have replaced weeks of training with a prompt for many low-volume tasks: classifying inspection photos, reading varied documents, and describing images for accessibility. Knowing how to request JSON and validate the output is what makes this reliable in a system.
Key concepts
🎯 Train on your data and measure
When the class you need isn’t in COCO—a specific defect in your part, a pest in your crop—the way forward is transfer learning: start with a pretrained model and fine-tune it with a few hundred annotated images. The model already knows how to recognize edges, textures, and shapes; you only teach it your classes. Tools like Label Studio and CVAT help you annotate (draw the correct boxes or masks), and the YOLO format stores each box as a line of text: class, center x, center y, width, and height, normalized from 0 to 1.
To measure performance, use three numbers. Precision tells you how many of the detections made were correct. Recall tells you how many of the objects that existed the model found. mAP (mean Average Precision) summarizes the balance between the two across all classes; mAP50 counts a detection as correct if its IoU with the correct box is at least 0.5, and mAP50-95 is more demanding, averaging across several IoU thresholds. Which metric matters more depends on the cost of an error: in safety inspections, missing a defect (low recall) is usually worse than a false alarm.
What it is
This is the customization cycle in computer vision: collect and annotate images from your scenario, fine-tune a pretrained model, and measure precision, recall, and mAP on a validation set that represents real-world use.
Collect. Photos from the real environment: the same camera, daytime and nighttime lighting, and difficult angles too.
Annotate. Written annotation guidelines (what counts as a defect?) and a second person reviewing a sample.
Fine-tune. Train from pretrained weights, using data augmentation (rotation, brightness, cropping) provided by the library.
Measure and intentionally make mistakes. Look at the images where the model made mistakes; the fix is almost always to annotate more cases like them.
Goal: run a short end-to-end training session and read the metrics.
# 1) test training run with coco8 (8 images, downloaded automatically) yolo detect train data=coco8.yaml model=yolo11n.pt epochs=3 imgsz=640 # 2) validate the best checkpoint and see precision (P), recall (R), mAP50, and mAP50-95 yolo detect val model=runs/detect/train/weights/best.pt data=coco8.yaml # 3) with YOUR dataset: create meu_dataset.yaml like this # path: <dataset folder> # train: images/train # val: images/val # names: # 0: <class_0, e.g. scratched> # 1: <class_1, e.g. dented> # (each image has a .txt file in labels/ with lines: class cx cy width height) yolo detect train data=meu_dataset.yaml model=yolo11n.pt epochs=50 imgsz=640
How to check: at the end of step 2, the terminal shows a table with the columns P, R, mAP50 e mAP50-95, by class and overall (all). The folder runs/detect/ stores charts and the confusion matrix. With only 3 epochs on coco8, the numbers will be low—the goal here is to see the cycle working, not the result.
✓ Honest validation
- ✓Validation images from different days and cameras than those used for training.
- ✓Metric chosen based on the business cost of errors.
- ✓Look at the errors, not just the average.
✗ Misleading metric
- ✗Nearly identical frames from the same video in both the training and validation sets.
- ✗High mAP for a rare class with three examples.
- ✗Testing only with attractive photos taken for the project.
Why learn
A ready-made model handles the general case; the project’s value comes from the classes and conditions in your situation. Knowing how to annotate, fine-tune, and interpret precision and recall lets you promise a result—and know when it still isn’t good enough.
Key concepts
⚖️ Production, ethics, and LGPD
Putting computer vision into production involves decisions that don't come up in a notebook. Where the model runs: at the edge (edge — on the device itself, near the camera, with low latency and without sending images elsewhere) or in the cloud (more computing power, higher network costs). How to handle video: instead of detecting objects in each frame without memory, tracking (tracking, using algorithms like ByteTrack, which ultralytics already includes) maintains each object's identity across frames—this lets you count people crossing a line without counting the same person twice.
Then there's drift (drift): the world changes, but the model doesn't. A new camera, lighting from another season, redesigned packaging—the model's accuracy quietly drops. Keep a sample of production images, review it periodically, and retrain when the metrics decline. For the human side, the most important rule in Brazil: under LGPD, biometric data —such as a face used to identify someone—counts as sensitive personal data, subject to stricter requirements for legal basis, transparency, and security.
What it is
This is the set of choices for operating computer vision in the real world: where to run it, how to track objects in video, how to detect and correct drift, and how to handle images of people under LGPD and with respect for those being filmed.
✓ Responsible use
- ✓Process images at the edge and store only the result (count, alert), not the image.
- ✓Blur faces and license plates when identity isn't needed.
- ✓Post a visible notice that the area is monitored and explain why.
- ✓Test the model with different groups of people before using it.
✗ Red line
- ✗Facial recognition without a legal basis or an impact assessment.
- ✗Automated decisions about people with no possibility of human review.
- ✗Keeping video “just in case,” with no disposal deadline.
- ✗Inferring someone’s emotions, health, or background from an image.
💡 Tip
Before proposing any system that identifies people, talk with the company’s data protection officer (DPO) and prepare a data protection impact report. Often, you can meet the business goal—counting foot traffic or measuring a line—without identifying anyone. That’s the cheaper, safer design.
Why learn
Most computer vision systems don’t fail because of the model; they fail because of latency, unmonitored drift, or a legal issue discovered too late. Designing the full cycle and privacy protections from the start is what helps a project survive its first year.
Key concepts
✅ Module summary
Next module:
2.7 — NLP and Text Processing 📝