Track C: Image analysis in Python

Track: Image analysis in Python

Introduction to agentic AI

About this lecture

Counting and measuring objects in images is a chore in many fields: nuclei in microscopy, colonies on plates, grains in a material. By hand it takes days and nobody counts the same way twice. A short Python script does it in seconds, the same way every time. In this track the agent writes the script and you check what it found.

  • An image is a table of numbers. Never edit the original; the script reads it and writes results elsewhere.
  • Pixels are not micrometres. Find the pixel size and convert, or every area is wrong.
  • Threshold, label, measure. Three steps turn an image into a table with one row per object.
  • Look at the outlines. Overlay what was found on the image, and count a few images by hand.
  • A count can be right for the wrong reasons. Merged and missed nuclei can cancel out.

This is a track and the course’s gentle introduction to Python: you read results, not code. The worked example uses real, annotated images, so you have a known answer.

Two hundred fields of nuclei: count them and measure them

The same steps count colonies, particles and cells

Python, just enough to read what the agent did

Word What it means here
Python a programming language; installed once on your computer
script a text file ending in .py with the steps; run it again and you get the same result
package a ready-made toolbox: scikit-image (image analysis), numpy (numbers), pandas (tables), matplotlib (plots)
virtual environment a folder (.venv) in your project holding the packages for this project only
notebook an alternative to a script, mixing code and output; we use scripts

You will not write Python. You will read file names, settings at the top of a script, tables and pictures, and you will ask the agent what a line does when it matters.

The pipeline: from an image to a table and a picture to check

The agent sets up a virtual environment*; you only need to know it exists

* With Rust, no virtual environment is needed: a Rust program compiles to one self-contained file. See Translating code to Rust.

A grey image is a table of numbers

A 16-bit image can look black and still be perfect

  • Many viewers show 16-bit files on a 0 to 65 535 scale. Values up to 4095 then look almost black.
  • Brighten the display, not the file. Use Fiji or ask the agent for a contrast-stretched preview copy.

File formats: keep the original, know what is in it

Format What it is Watch out for
TIFF (.tif) the common lossless format for microscopy; 8 or 16 bits can hold several channels or a stack; metadata may or may not include pixel size
Vendor formats (.czi Zeiss, .nd2 Nikon, .lif Leica) the microscope’s own format, with full metadata need an extra reader (Bio-Formats in Fiji, or a Python package the agent installs); check that channels come out in the right order
PNG lossless, usually 8 bits 16-bit data squeezed into 8 bits loses detail; fine for previews and masks
JPEG lossy compression never for analysis: it changes pixel values, worst at edges

Ask the agent to report the shape, bit depth and value range of the first image before anything else.

Never edit the raw images: the script reads, results go elsewhere

Pixels are not micrometres: find the pixel size and convert

The known answer: people outlined every nucleus by hand

  • BBBC039: 200 images, about 23 000 nuclei outlined by people. Licence CC0 (no restrictions); please cite it.
  • The masks use a few colours, reused: one colour is not one nucleus. Decoding them is a step you check too.

First prompt: have the agent describe the images back to you

data/raw/ holds microscopy images (images/*.tif) and hand-drawn ground
truth masks (masks/*.png) from the public dataset BBBC039. Do not
analyse anything yet. Set up a Python virtual environment in this
folder with scikit-image, numpy, pandas and matplotlib, and record the
packages in requirements.txt.

Then tell me: how many images and masks there are, and whether every
image has a mask with the same name; the size, bit depth and value range
of the first image; and how the masks encode the nuclei. Make
contrast-stretched preview PNGs of the first 3 images in results/previews/.
Do not change anything in data/raw.

What you check: 200 images and 200 masks with matching names (and no stray __MACOSX files counted as images), 520 x 696 pixels, 16-bit, values up to 4095.

A threshold splits pixels into nucleus and background

  • Otsu’s method picks the cut that best separates the two humps of the histogram. One number per image, chosen by the data.
  • It assumes two kinds of pixel. Very uneven background or very dim nuclei break that assumption.

Threshold, then label: every connected blob gets a number

Each object becomes one row in a table

The overlay shows what the script found

Touching nuclei merge; a watershed split separates most of them

What counts as one nucleus is a definition, not a detail

  • In A12_s7 the compound fragmented many nuclei. The people who drew the masks outlined each fragment: 69 objects. A simple script finds 18.
  • Neither is “wrong”. Decide what you count, write it down, and check that the script and the truth use the same rule.

Uneven lighting and dim nuclei need more than one global threshold

  • One global threshold is one number for the whole image. Nuclei in a dim corner fall below it, and bright background can rise above it.
  • Fixes: remove the background first (an “opening” or “top-hat” filter), or a local threshold. Check either on the overlay.

Debris and border objects are decisions, not details

A count can be right for the wrong reasons

  • A16_s2: 94 found, 93 true. But 11 of the 94 are specks of debris, and merged pairs hide about as many real nuclei.
  • Most images: 10 to 40 too few, because crowded nuclei merge. A12_s7: fragments (previous slides).

Compare with hand counts on images the script was not tuned on

  • Points on the diagonal: same count as the people who drew the masks.
  • Tune the settings on a few images, check on others. BBBC039 has a ready-made split: training, validation, test.

One script processes the whole folder with the same settings

Plot the distribution, and compare it with the truth

Your own images: what you may send, and what to keep

  • Cell lines, model organisms, plates, materials: usually fine as internal research data.
  • Images of patient tissue or people: personal data, sometimes health data. Histology slides, fundus images, photos with faces.
  • Metadata leaks: file names, TIFF tags and vendor files can hold patient IDs, user names and dates. Check before sharing.
  • Size: the agent does not need to read every image. It needs a few examples and a script that runs locally on all of them.
  • When in doubt, develop on a public look-alike (BBBC has many) and run the script yourself on the real images.

Where this goes wrong

  • Edited originals. A brightened or converted copy saved over the raw image. Every intensity changes.
  • JPEG or 8-bit copies analysed instead of the 16-bit original.
  • Pixels reported as micrometres, or the pixel size not squared for areas.
  • Merged nuclei. Undercount and doubled areas, worst in crowded images.
  • Missed dim nuclei. One global threshold on an uneven image.
  • Debris counted, border objects measured. Size and border rules not decided.
  • Errors that cancel. The count looks right; the overlay shows it is not.
  • Tuned on the test images, or tuned per image. Results that will not hold on new data.
  • Hidden junk files (__MACOSX, Thumbs.db) read as images.

Summary

Concept Key fact
Python, just enough script, packages, a virtual environment the agent sets up
An image is numbers 16-bit values; brighten the display, never the file
Raw images read-only; results written elsewhere, remade by the script
Pixel size find it and its source; areas use the pixel size squared
Threshold, label, measure Otsu splits pixels; labels make objects; one row per object
Overlay outlines on the image: merges, misses and debris at a glance
Touching, dim, fragmented watershed split; background removal; a stated definition
Known answer hand-drawn masks (decoded and checked) or your own hand counts
Tune and test adjust on some images, check on others
Batch one script, same settings, rows = images

Next (Track D: Survey and tabular data, or any other track): the same habits on another kind of data. Or apply this track to your own images.