Skip to main content

Image Processing

In this class we step away a little from “pure” remote sensing (bands, spectral indices) and go back to the basics of image processing. Deep down, every satellite image is also just… an image. The same tools that process a photo from your phone can process a satellite scene.

For today’s class we’ll use two extremely common image processing libraries.

Today’s plan: 1. Image = numpy array (again, because why not) 2. OpenCV vs scikit-image 3. Cropping 4. Grayscale 5. Histogram and equalization 6. Brightness/contrast correction 7. Resizing and rescaling 8. Kernels and blurring (including Gaussian blur) 9. Edge detection (Sobel, Canny) 10. Connected Component Analysis 11. Connecting everything to the preprocessing used to train neural networks

We’ll use a real satellite image (a CBERS-4/MUX quicklook) as our “guinea pig”, but today it will be treated like any other image (a regular PNG): no rasterio, no spectral bands. Just pixels.

Code
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, color, exposure, filters, feature, measure, transform

print("OpenCV:", cv2.__version__)
import skimage
print("scikit-image:", skimage.__version__)
OpenCV: 5.0.0
scikit-image: 0.26.0

Today’s image

It’s a quicklook (a ready-made PNG, like a “photo” of the scene) of a CBERS-4/MUX scene over the Novo Progresso (PA) region, the same deforestation area we saw in the STAC class. But today, instead of downloading separate bands with rasterio, we go straight to the PNG, like any image.

Code
import os
import requests

img_dir = "images"
os.makedirs(img_dir, exist_ok=True)
img_path = os.path.join(img_dir, "cbers4_novo_progresso_2023.png")

if not os.path.exists(img_path):
    url = ("https://data.inpe.br/bdc/data/cbers4/2023_07/CBERS_4_MUX_DRD_2023_07_18.13_49_30_CB11/"
           "167_109_0/4_BC_UTM_WGS84/CBERS_4_MUX_20230718_167_109.png")
    resp = requests.get(url, timeout=30)
    with open(img_path, "wb") as f:
        f.write(resp.content)

print("file:", img_path, "-", os.path.getsize(img_path) / 1024, "KB")
arquivo: images/cbers4_novo_progresso_2023.png - 379.935546875 KB

An image is nothing more than a numpy array

It’s worth getting this idea firmly into your head (based on: scikit-image — Images are numpy arrays):

  • A color image is a 3D array: (height, width, channels), usually 3 channels (R, G, B);
  • Each pixel is a number from 0 to 255 (when the image is uint8, i.e. 8 bits);
  • image[row, column] gives you a pixel (an array of 3 numbers); image[row, column, channel] gives you a single number;
  • Since it’s numpy, everything you already know about slicing and indexing works: cutting out pieces, taking a single channel, flipping, etc.
Code
img_rgb = skimage.io.imread(img_path)[:, :, :3]  # drop the alpha channel, if any
Code
img_rgb.shape
(582, 611, 3)
Code
# Getting a pixel - this shows the 3 channels (RGB)
img_rgb[100,200]
array([ 75, 163, 124], dtype=uint8)
Code
img_rgb[100,200,1]
np.uint8(163)
Code
plt.imshow(img_rgb)

Code

fig, axes = plt.subplots(1, 4, figsize=(16, 4))
axes[0].imshow(img_rgb)
axes[0].set_title("Full RGB")
for ax, ch, nome, cmap in zip(axes[1:], range(3), ["Red (R)", "Green (G)", "Blue (B)"],
                                ["Reds", "Greens", "Blues"]):
    ax.imshow(img_rgb[:, :, ch], cmap=cmap)
    ax.set_title(nome)
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

2. The BGR gotcha

For historical reasons (old cameras, libraries from 20+ years ago), OpenCV reads and writes color images in BGR order (blue, green, red), the opposite of practically the rest of the Python world (skimage, matplotlib, PIL), which uses RGB.

This is a classic source of bugs, so watch out! If you read with cv2.imread and show it directly with matplotlib, the colors come out swapped (with a weird bluish tint).

Code
img_bgr = cv2.imread(img_path)  # OpenCV already reads in BGR

# notice how cv2 has a slightly different style from other Python libraries
img_bgr_para_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)

print("same as what skimage read?", np.array_equal(img_bgr_para_rgb, img_rgb))

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(img_bgr)  # wrong on purpose!
axes[0].set_title("BGR")
axes[1].imshow(img_bgr_para_rgb)
axes[1].set_title("COLOR_BGR2RGB)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()
são iguais ao lido pelo skimage? True

3. Cropping

Cropping is basically cutting out the piece of the image we’re interested in. It can be done very easily with simple array indexing,

like: image[row_start:row_end, col_start:col_end].

Code
img = img_rgb[220:480, 120:520]  # from here on, "img" is our working image
Code
img = img_rgb[220:480, 120:520]  # from here on, "img" is our working image

fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].imshow(img_rgb)
axes[0].set_title(f"Original {img_rgb.shape[:2]}")
axes[1].imshow(img)
axes[1].set_title(f"Cropped {img.shape[:2]}")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Grayscale

If we have an RGB image with three channels, we can convert it to grayscale. However, this isn’t just the average of the three channels, because that doesn’t replicate how the human eye behaves. We need a weighted average; the weights are well established in the literature, and both libraries have functions to do the conversion very simply.

The human eye is more sensitive to green than to blue, for example. That’s why a weighted average is used:

\[\text{gray} = 0.299 \times R + 0.587 \times G + 0.114 \times B\]

Both OpenCV and scikit-image already implement this for you.

Code
# first read the image and convert it to gray
gray_cv = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)     # uint8, 0-255

# converts to gray and scales to 0-1 in one go 
gray_sk = color.rgb2gray(img)                        # float, 0.0-1.0
Code
print("cv2:     dtype =", gray_cv.dtype, "| min/max =", gray_cv.min(), gray_cv.max())
print("skimage: dtype =", gray_sk.dtype, "| min/max =", round(gray_sk.min(), 3), round(gray_sk.max(), 3))
cv2:     dtype = uint8 | min/max = 71 213
skimage: dtype = float64 | min/max = 0.261 0.835
Code
gray_cv = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)     # uint8, 0-255
gray_sk = color.rgb2gray(img)                        # float, 0.0-1.0

print("cv2:     dtype =", gray_cv.dtype, "| min/max =", gray_cv.min(), gray_cv.max())
print("skimage: dtype =", gray_sk.dtype, "| min/max =", round(gray_sk.min(), 3), round(gray_sk.max(), 3))

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(gray_cv, cmap="gray")
axes[0].set_title("cv2.cvtColor (uint8, 0-255)")
axes[1].imshow(gray_sk, cmap="gray")
axes[1].set_title("skimage.color.rgb2gray (float, 0-1)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()
cv2:     dtype = uint8 | min/max = 71 213
skimage: dtype = float64 | min/max = 0.261 0.835

Code
# let's try the same with scikit-image
gray_skimage = skimage.color.rgb2gray(img_rgb)
plt.imshow(gray_skimage, cmap='gray')

Brightness and contrast correction

Converting to floating point in [0, 1]

To make the arithmetic in the next sections (brightness and contrast) easier, we’ll convert the image to floating point, with values between 0 and 1, using img_as_float. This avoids the integer overflow problems we saw earlier and makes the formulas much easier to understand.

Code
from skimage import img_as_float

# Converting to floating point, in the [0, 1] range
image = img_as_float(img)

plt.imshow(image)
plt.axis("off")
plt.show()

Brightness correction

Brightness is related to the intensity of the values. If our image is uint8, its scale goes from 0 to 255, where zero is the darkest intensity and 255 the brightest. To increase brightness, we push these values closer to 255.

0       - black
50      - dark gray
128     - medium gray
200     - light gray
255     - white

So brightness answers the question of whether the image is generally lighter or darker.

The simplest way to change brightness is to add (or subtract) a constant to every pixel:

\[ I_{new} = I + \beta \]

where \(\beta\) controls the brightness.

Code
brilho = 0.2

mais_claro = np.clip(image + brilho, 0, 1)
mais_escuro = np.clip(image - brilho, 0, 1)

np.clip() is essential here: valid image intensities must stay between 0 and 1; without it, values like 1.1 or -0.05 would break the visualization

We can visualize the results:

Code
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].imshow(image)
axes[0].set_title("Original")

axes[1].imshow(mais_claro)
axes[1].set_title("Brighter")

axes[2].imshow(mais_escuro)
axes[2].set_title("Darker")

for ax in axes:
    ax.axis("off")

plt.tight_layout()
plt.show()

Note: for an 8-bit grayscale image (uint8), the equivalent operation would be:

mais_claro = np.clip(image + 30, 0, 255)

The core idea doesn’t change: brightness is a change in the overall level of intensity.

Code
# Once we've increased an image's brightness, we can mask just the high-intensity pixels
mais_claro[mais_claro<0.7]=0
plt.imshow(mais_claro)

Contrast correction

Contrast is a shift of values away from a central value. So contrast answers the question of how different the values are between the lightest and darkest regions.

Contrast can be changed by multiplying the pixel values around a central value:

\[ I_{new} = \alpha(I - c) + c \]

where:

  • \(\alpha > 1\) → increases contrast
  • \(0 < \alpha < 1\) → decreases contrast
  • \(c\) → reference intensity, usually 0.5
Code
contraste = 1.5

alto_contraste = np.clip(
    contraste * (image - 0.5) + 0.5,
    0,
    1
)
Code
# To reduce contrast

contraste = 0.3
baixo_contraste = np.clip(
    contraste * (image - 0.5) + 0.5,
    0,
    1
)

Why subtract and add 0.5?

Take a pixel with value 0.7:

0.7 - 0.5 = 0.2
0.2 × 1.5 = 0.3
0.3 + 0.5 = 0.8

The pixel moves away from the midpoint, increasing contrast.

Likewise, a pixel of 0.3 becomes 0.2, moving away from the midpoint in the opposite direction.

Code
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].imshow(image)
axes[0].set_title("Original")

axes[1].imshow(alto_contraste)
axes[1].set_title("High contrast (α=1.5)")

axes[2].imshow(baixo_contraste)
axes[2].set_title("Low contrast (α=0.5)")

for ax in axes:
    ax.axis("off")

plt.tight_layout()
plt.show()

Contrast stretching

A particularly instructive technique is contrast stretching. scikit-image provides it ready-made in exposure.rescale_intensity():

Code
from skimage import exposure

esticada = exposure.rescale_intensity(
    image,
    in_range=(0.2, 0.8),
    out_range=(0, 1)
)

plt.imshow(esticada)
plt.axis("off")
plt.show()

Here, pixels near 0.2 become black and pixels near 0.8 become white.

This is useful when the image only occupies a small part of the available intensity range.

Automatic contrast stretching

Instead of picking 0.2 and 0.8 by hand, we can compute useful limits from the image itself, for example using percentiles:

Code
np.percentile(image, 2)
np.float64(0.1411764705882353)
Code
baixo = np.percentile(image, 2)
alto = np.percentile(image, 98)

esticada_automatica = exposure.rescale_intensity(
    image,
    in_range=(baixo, alto),
    out_range=(0, 1)
)

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(image)
axes[0].set_title("Original")
axes[1].imshow(esticada)
axes[1].set_title("Manual stretching (0.2-0.8)")
axes[2].imshow(esticada_automatica)
axes[2].set_title("Automatic stretching (percentiles 2-98)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

The 2nd percentile becomes roughly black and the 98th percentile roughly white.

This usually works better than using the absolute minimum and maximum, because a few extreme pixels don’t end up dominating the whole transformation.

Histogram and equalization

An image histogram is just a count of how many pixels have each intensity value (0 to 255). Low-contrast, somewhat blurry images (very common in satellite images with atmospheric haze) have a histogram concentrated in a narrow range.

We’ve already seen one way to fix this: changing an image’s contrast and brightness.

Another very common way is histogram equalization.

Histogram equalization redistributes these intensities to fill the whole 0-255 range, “stretching” the contrast. Let’s compare three versions: - cv2.equalizeHist — classic global equalization; - skimage.exposure.equalize_hist — the scikit-image equivalent; - equalize_adapthist (CLAHE) — adaptive equalization, computed in blocks of the image. It usually works better when contrast varies from one region to another (e.g. clouds on one side, shadow on the other).

Code
eq_cv = cv2.equalizeHist(gray_cv)
eq_sk = exposure.equalize_hist(gray_cv)
eq_clahe = exposure.equalize_adapthist(gray_cv, clip_limit=0.03)

fig, axes = plt.subplots(2, 4, figsize=(16, 8))
for ax, imagem, titulo in zip(axes[0], [gray_cv, eq_cv, eq_sk, eq_clahe],
                                ["Original", "cv2.equalizeHist", "skimage.equalize_hist", "CLAHE (adaptive)"]):
    ax.imshow(imagem, cmap="gray")
    ax.set_title(titulo)
    ax.axis("off")

for ax, imagem, titulo in zip(axes[1], [gray_cv, eq_cv, eq_sk, eq_clahe],
                                ["Original", "cv2.equalizeHist", "skimage.equalize_hist", "CLAHE (adaptive)"]):
    ax.hist(np.asarray(imagem).ravel(), bins=64)
    ax.set_title(f"histogram — {titulo}")

plt.tight_layout()
plt.show()

The math behind histogram equalization

The equalization we just saw (cv2.equalizeHist, equalize_hist, CLAHE) isn’t magic. Let’s rebuild the pipeline from scratch, step by step, using our grayscale uint8 image with values 0-255:

Image
  ↓
Histogram
  ↓
Normalized histogram (PMF)
  ↓
CDF
  ↓
Mapping function
  ↓
New intensities
  ↓
Equalized image

The histogram counts how many pixels have each intensity \(r_k\), for \(k = 0, 1, \dots, L-1\) (with \(L = 256\) levels):

\[ h(r_k) = \#\{(i,j) \;:\; I(i,j) = r_k\} \]

Summing all the histogram bins gives back the total number of pixels in the image (\(M \times N\)):

\[ \sum_{k=0}^{L-1} h(r_k) = M \times N \]

Code


M, N = gray_cv.shape
L = 256

histograma, bins = np.histogram(gray_cv.ravel(), bins=L, range=(0, L))

print("total pixels (M x N):", M * N)
print("histogram sum:          ", histograma.sum())

plt.figure(figsize=(8, 4))
plt.bar(np.arange(L), histograma, width=1, color="steelblue")
plt.title("Histogram — $h(r_k)$")
plt.xlabel("Intensity $r_k$")
plt.ylabel("Number of pixels")
plt.show()
total de pixels (M x N): 104000
soma do histograma:      104000

Dividing each \(h(r_k)\) by the total number of pixels turns counts into a probability distribution: the probability that any given pixel of the image has intensity \(r_k\):

\[ p(r_k) = \frac{h(r_k)}{M \times N} \]

Since \(h(r_k) \geq 0\) and the sum of all \(h(r_k)\) is \(M \times N\) (Step 1), we have the two properties of a valid PMF:

\[ p(r_k) \geq 0 \quad \text{and} \quad \sum_{k=0}^{L-1} p(r_k) = 1 \]

Code

pmf = histograma / (M * N)
print("PMF sum:", pmf.sum())  # should be (very close to) 1.0

plt.figure(figsize=(8, 4))
plt.bar(np.arange(L), pmf, width=1, color="darkorange")
plt.title("Normalized histogram — $p(r_k)$")
plt.xlabel("Intensity $r_k$")
plt.ylabel("Probability")
plt.show()
soma da PMF: 1.0

The CDF accumulates the probability of a pixel having intensity up to \(r_k\):

\[ c(r_k) = \sum_{j=0}^{k} p(r_j) \]

Two properties follow directly from this sum:

  • Monotonically non-decreasing: \(c(r_k) \geq c(r_{k-1})\), since we only add terms \(\geq 0\).
  • Ends at 1: \(c(r_{L-1}) = \sum_{j=0}^{L-1} p(r_j) = 1\) (it’s the complete sum of the PMF from Step 2).
Code


cdf = np.cumsum(pmf)
print("c(r_0)   =", round(cdf[0], 4))
print("c(r_255) =", round(cdf[-1], 4))

plt.figure(figsize=(8, 4))
plt.plot(np.arange(L), cdf, color="seagreen", drawstyle="steps-post")
plt.title("CDF — $c(r_k)$")
plt.xlabel("Intensity $r_k$")
plt.ylabel("Cumulative probability")
plt.ylim(0, 1.05)
plt.show()
c(r_0)   = 0.0
c(r_255) = 1.0

The idea of equalization is to use the CDF itself as the transformation function, rescaled to the intensity range

\([0, L-1]\) (0-255):

\[ T(r_k) = \text{round}\big((L-1)\, c(r_k)\big) \]

Multiplying the CDF by the number of levels maps the intensities so that the output histogram becomes (approximately) uniform. Basically, in this step we apply a function that maps the CDF onto a uniform distribution.

Code
T = np.round((L - 1) * cdf).astype(np.uint8)

plt.figure(figsize=(8, 4))
plt.plot(np.arange(L), T, color="firebrick")
plt.plot([0, L - 1], [0, L - 1], "--", color="gray", linewidth=1, label="identity (no change)")
plt.title("Mapping function — $T(r_k)$")
plt.xlabel("Original intensity $r_k$")
plt.ylabel("New intensity $T(r_k)$")
plt.legend()
plt.show()

Finally, we apply \(T\) pixel by pixel, replacing each intensity \(r_k\) with its new intensity \(T(r_k)\) (a simple lookup table):

\[ I_{eq}(i, j) = T\big(I(i, j)\big) \]

Code
gray_equalizado_na_mao = T[gray_cv]  # Lookup table - LUT: replaces each pixel with its mapped value

fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].imshow(gray_cv, cmap="gray")
axes[0, 0].set_title("Original")
axes[0, 1].imshow(gray_equalizado_na_mao, cmap="gray")
axes[0, 1].set_title("Equalized (by hand, step by step)")
axes[1, 0].hist(gray_cv.ravel(), bins=64, color="steelblue")
axes[1, 0].set_title("Original histogram")
axes[1, 1].hist(gray_equalizado_na_mao.ravel(), bins=64, color="firebrick")
axes[1, 1].set_title("Equalized histogram (more spread out)")
for ax in axes[0]:
    ax.axis("off")
plt.tight_layout()
plt.show()

A small numerical example:

Given the 4x4 matrix M with 16 pixels:

0 0 1 1 1 2 2 2 3 3 4 5 5 5 6 7

The histogram of this matrix is:

Intensity (r) Count (n_r)
0 2
1 3
2 3
3 2
4 1
5 3
6 1
7 1

Normalizing this matrix

$ p(r)=n_r/16 $

the table becomes: | (r) | (p(r)) | CDF | | —-: | ——-: | —–: | | 0 | 0.125 | 0.125 | | 1 | 0.1875 | 0.3125 | | 2 | 0.1875 | 0.5000 | | 3 | 0.125 | 0.6250 | | 4 | 0.0625 | 0.6875 | | 5 | 0.1875 | 0.8750 | | 6 | 0.0625 | 0.9375 | | 7 | 0.0625 | 1.0000 |

Since the maximum intensity in our histogram is 7 (L-1), we can compute the transform T

$ T = 7×CDF(r)$

and so our new equalized matrix becomes:

Original (r) CDF New (s)
0 .125 .875
1 .3125 2.1875
2 .5 3.5
3 .625 4.375
4 .6875 4.8125
5 .875 6.125
6 .9375 6.5625
7 1.0 7

All that’s left is to round these mapped numbers.

Resizing and rescaling

Both do essentially the same thing, resampling an image onto another pixel grid, but with a small difference:

  • resize: you specify the exact final size (e.g. 224x224), which is what almost every neural network expects as input;
  • rescale: you specify a scale factor (e.g. 0.5 = half the size) and the function keeps the original aspect ratio.

Resizing always needs an interpolation method: since we’re going from one number of pixels to another, we have to interpolate the pixels onto the new grid. The interpolation method also matters: INTER_NEAREST (“blocky”), INTER_LINEAR/INTER_CUBIC (smoother), INTER_AREA (best for shrinking the image).

Code
resized = cv2.resize(img, 
                     (224, 224), 
                     interpolation=cv2.INTER_AREA)  # fixed size
rescaled = transform.rescale(img, 
                             0.5, 
                             channel_axis=-1, 
                             anti_aliasing=True)  # half the size, same aspect ratio

print("original:", img.shape)
print("resize to 224x224:", resized.shape)
print("rescale by 0.5:", rescaled.shape)

fig, axes = plt.subplots(1, 3, figsize=(14, 5))
axes[0].imshow(img)
axes[0].set_title(f"Original {img.shape[:2]}")
axes[1].imshow(resized)
axes[1].set_title(f"resize  {resized.shape[:2]}")
axes[2].imshow(rescaled)
axes[2].set_title(f"rescale (x0.5)  {rescaled.shape[:2]}")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()
original: (260, 400, 3)
resize p/ 224x224: (224, 224, 3)
rescale por 0.5: (130, 200, 3)

Code
resized = cv2.resize(img, 
                     (224, 224), 
                     interpolation=cv2.INTER_AREA)  # fixed size
resized2 = cv2.resize(img, 
                     (512, 512), 
                     interpolation=cv2.INTER_AREA)  # half the size, same aspect ratio

print("original:", img.shape)
print("resize to 224x224:", resized.shape)
print("rescale by 0.5:", rescaled.shape)

fig, axes = plt.subplots(1, 3, figsize=(14, 5))
axes[0].imshow(img)
axes[0].set_title(f"Original {img.shape[:2]}")
axes[1].imshow(resized)
axes[1].set_title(f"{resized.shape[:2]}")
axes[2].imshow(resized2)
axes[2].set_title(f" {resized2.shape[:2]}")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()
original: (260, 400, 3)
resize p/ 224x224: (224, 224, 3)
rescale por 0.5: (130, 200, 3)

8. Kernels

Visual explanation of kernels: SETOSA

What is a kernel?

A kernel (or filter) is just a small matrix (like 3x3 or 5x5) of numbers. The convolution operation slides this kernel over every pixel of the image and, at each position, computes a “weighted average” of the neighborhood: it multiplies each neighboring pixel by the corresponding number in the kernel, adds everything up, and that is the output pixel’s value.

What changes from one effect to another is only the content of the kernel:

  • Box blur kernel: all values equal (e.g. 1/9 in a 3x3 matrix). Each pixel becomes the average of its neighbors, which produces the blur effect.
  • Sharpen kernel: a high value in the center, negative at the edges. This exaggerates the difference between a pixel and its neighbors, enhancing details.
  • Edge kernels (Sobel, which we’ll see shortly): detect abrupt changes in intensity.

What about Gaussian Blur?

The “box blur” gives the same weight to every neighbor, which can make the result look a bit “blocky”. Gaussian blur uses a kernel whose weights follow a bell curve (normal/Gaussian distribution): the central pixel weighs the most, and neighbors weigh less and less the farther away they are. The result is a smoother, more “natural” blur.

The sigma parameter controls the width of the bell: small sigma = narrow bell = weak blur; large sigma = wide bell = strong blur. Gaussian blur is used all the time as preprocessing to reduce noise before other operations (such as edge detection, which we’ll see next).

Code
import marimo as mo
from scipy.signal import convolve2d
from skimage import data, color
from PIL import Image
import matplotlib.pyplot as plt
import io
import urllib.request
Code
kernels_3x3 = {
    "Identity": np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=float),
    "Box Blur": np.ones((3, 3), dtype=float) / 9,
    "Gaussian Blur": np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], dtype=float) / 16,
    "Sharpen": np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=float),
    "Edge Detect": np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype=float),
    "Emboss": np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]], dtype=float),
    "Sobel X": np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float),
    "Sobel Y": np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=float),
}

kernels_5x5 = {
    "Identity": np.array(
        [
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0],
        ],
        dtype=float,
    ),
    "Box Blur": np.ones((5, 5), dtype=float) / 25,
    "Gaussian Blur": np.array(
        [
            [1, 4, 6, 4, 1],
            [4, 16, 24, 16, 4],
            [6, 24, 36, 24, 6],
            [4, 16, 24, 16, 4],
            [1, 4, 6, 4, 1],
        ],
        dtype=float,
    )
    / 256,
    "Sharpen": np.array(
        [
            [0, 0, -1, 0, 0],
            [0, -1, -1, -1, 0],
            [-1, -1, 13, -1, -1],
            [0, -1, -1, -1, 0],
            [0, 0, -1, 0, 0],
        ],
        dtype=float,
    ),
    "Edge Detect": np.array(
        [
            [-1, -1, -1, -1, -1],
            [-1, -1, -1, -1, -1],
            [-1, -1, 24, -1, -1],
            [-1, -1, -1, -1, -1],
            [-1, -1, -1, -1, -1],
        ],
        dtype=float,
    ),
    "Emboss": np.array(
        [
            [-2, -1, -1, 0, 0],
            [-1, -1, 0, 1, 0],
            [-1, 0, 1, 0, 1],
            [0, -1, 0, 1, 1],
            [0, 0, 1, 1, 2],
        ],
        dtype=float,
    ),
    "Sobel X": np.array(
        [
            [-1, -2, 0, 2, 1],
            [-4, -8, 0, 8, 4],
            [-6, -12, 0, 12, 6],
            [-4, -8, 0, 8, 4],
            [-1, -2, 0, 2, 1],
        ],
        dtype=float,
    ),
    "Sobel Y": np.array(
        [
            [-1, -4, -6, -4, -1],
            [-2, -8, -12, -8, -2],
            [0, 0, 0, 0, 0],
            [2, 8, 12, 8, 2],
            [1, 4, 6, 4, 1],
        ],
        dtype=float,
    ),
}

kernels = {"3x3": kernels_3x3, "5x5": kernels_5x5}
Code
kernel_size_dropdown = mo.ui.dropdown(
    options=["3x3", "5x5"],
    value="3x3",
    label="Kernel size",
)
Code
kernel_dropdown = mo.ui.dropdown(
    options=list(kernels[kernel_size_dropdown.value].keys()),
    value="Identity",
    label="Kernel preset",
)
Code
selected_kernel = kernels[kernel_size_dropdown.value][kernel_dropdown.value]
kernel_matrix = mo.ui.matrix(
    selected_kernel.tolist(),
    min_value=-50,
    max_value=50,
    step=0.25,
    precision=2,
    label=f"**{kernel_dropdown.value}** kernel",
)
Code
loaders = {
    "Astronaut": lambda: color.rgb2gray(data.astronaut()),
    "Camera": lambda: data.camera() / 255.0,
    "Coins": lambda: data.coins() / 255.0,
    "Cat": lambda: color.rgb2gray(data.cat()),
    "Coffee": lambda: color.rgb2gray(data.coffee()),
}

if image_dropdown.value == "Custom URL" and url_input.value:
    with urllib.request.urlopen(url_input.value) as response:
        img_bytes = response.read()
    pil_img = Image.open(io.BytesIO(img_bytes)).convert("L")
    gray_image = np.array(pil_img) / 255.0
else:
    loader = loaders.get(image_dropdown.value, loaders["Astronaut"])
    gray_image = loader()
Code
image_options = ["Astronaut", "Camera", "Coins", "Cat", "Coffee", "Custom URL"]
image_dropdown = mo.ui.dropdown(
    options=image_options,
    value="Astronaut",
    label="Image",
)
url_input = mo.ui.text(
    placeholder="https://example.com/image.jpg",
    label="Image URL",
)

loaders = {
    "Astronaut": lambda: color.rgb2gray(data.astronaut()),
    "Camera": lambda: data.camera() / 255.0,
    "Coins": lambda: data.coins() / 255.0,
    "Cat": lambda: color.rgb2gray(data.cat()),
    "Coffee": lambda: color.rgb2gray(data.coffee()),
}

if image_dropdown.value == "Custom URL" and url_input.value:
    with urllib.request.urlopen(url_input.value) as response:
        img_bytes = response.read()
    pil_img = Image.open(io.BytesIO(img_bytes)).convert("L")
    gray_image = np.array(pil_img) / 255.0
else:
    loader = loaders.get(image_dropdown.value, loaders["Astronaut"])
    gray_image = loader()
Code
kernel = np.array(kernel_matrix.value)
convolved = convolve2d(gray_image, kernel, mode="same", boundary="symm")
convolved_clipped = np.clip(convolved, 0, 1)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 7))
ax1.imshow(gray_image, cmap="gray", vmin=0, vmax=1)
ax1.set_title("Original")
ax1.axis("off")
ax2.imshow(convolved_clipped, cmap="gray", vmin=0, vmax=1)
ax2.set_title("Convolved")
ax2.axis("off")
plt.tight_layout()

Code
controls = [image_dropdown]
if image_dropdown.value == "Custom URL":
    controls.append(url_input)
Code
mo.vstack(
    [
        mo.md("## Presets"),
        mo.hstack([kernel_size_dropdown, kernel_dropdown] + controls),
        mo.md("<br>"),
        mo.md("## Effect of the Kernel"),
        mo.hstack([kernel_matrix, mo.hstack([fig])]),
    ]
)

Presets


Effect of the Kernel

Code
# a sharpen kernel "by hand", applied with cv2.filter2D
kernel_sharpen = np.array([
    [ 0, -1,  0],
    [-1,  5, -1],
    [ 0, -1,  0],
])
sharpened = cv2.filter2D(img, ddepth=-1, kernel=kernel_sharpen)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(img)
axes[0].set_title("Original")
axes[1].imshow(sharpened)
axes[1].set_title("cv2.filter2D + sharpen kernel")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Code
# comparing different Gaussian blur sigmas
sigmas = [1, 3, 8]

fig, axes = plt.subplots(1, len(sigmas) + 1, figsize=(16, 4))
axes[0].imshow(img)
axes[0].set_title("Original (sigma=0)")
for ax, sigma in zip(axes[1:], sigmas):
    borrada = cv2.GaussianBlur(img, ksize=(0, 0), sigmaX=sigma)  # ksize=(0,0) -> computed from sigma
    ax.imshow(borrada)
    ax.set_title(f"Gaussian blur, sigma={sigma}")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Blurring only part of the image

So far we’ve blurred the whole image. But a kernel knows nothing about the “whole image”: it only sees the array you give it. If you give it just a small piece (a slice of the array), it blurs only that piece. That’s exactly how the face/license plate blurring you see on Google Street View works: find the region of interest, apply the blur only there, and put it back.

Let’s do this for real, with a real aerial image, and with a real reason for selective blurring: privacy. Drone/aerial images capture people and vehicles unintentionally, and selective blurring is how they are anonymized before publishing.

Where the image comes from: OpenAerialMap

OpenAerialMap (OAM) is an open catalog of aerial/drone imagery. Here we’ll use its REST API (api.openaerialmap.org/meta) through requests.

Code
# a broad bbox covering part of Brazil (southwestern Pará)
bbox_brasil = [-53, -11, -43, -1]

resp = requests.get("https://api.openaerialmap.org/meta", params={"bbox": ",".join(map(str, bbox_brasil)), "limit": 5})
resultados = resp.json()["results"]

for r in resultados:
    props = r["properties"]
    print(f"{r['title']:15s} | gsd={props.get('resolution_in_meters', 0)*100:.1f} cm | "
          f"dimensions={props.get('dimensions')} | {r['uuid']}")
gb_voo13        | gsd=1.5 cm | dimensões=[15378, 13484] | https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/6696e7f41684770001c339f5/2/6696e7f41684770001c339f8.tif
gb_voo24        | gsd=1.5 cm | dimensões=[15530, 13085] | https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/66979b821684770001c33a21/3/66979b821684770001c33a25.tif
gb_voo28        | gsd=1.5 cm | dimensões=[13156, 15028] | https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/66979b821684770001c33a21/7/66979b821684770001c33a29.tif
gb_voo01        | gsd=1.5 cm | dimensões=[15219, 13797] | https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/669677151684770001c339d2/0/669677151684770001c339d3.tif
gb_voo21        | gsd=1.5 cm | dimensões=[13014, 15280] | https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/66979b821684770001c33a21/0/66979b821684770001c33a22.tif

Reading just a piece, with rasterio

gb_voo13 is a giant drone image with more than 15,000 x 13,000 pixels (remember the RAM problem from the STAC class?). Again, we’ll access just a small piece of the image with a Window, reading only the region of interest, straight from the URL.

I looked earlier and know there’s a person in a planted field, near pixel (6320, 7020). So we’ll read a 500x500 pixel window around that point.

Code
import rasterio
from rasterio.windows import Window

oam_url = resultados[0]["uuid"]  # direct href to the GeoTIFF on S3, no STAC needed

with rasterio.open(oam_url) as src:
    print("full image dimensions:", src.width, "x", src.height, f"({src.width * src.height / 1e6:.0f} million pixels)")

    col_centro, row_centro = 6320, 7020
    janela = Window(col_centro - 250, row_centro - 250, 500, 500)
    aerea = src.read(window=janela)  # (bands, rows, columns)
    aerea = np.transpose(aerea, (1, 2, 0))  # -> (rows, columns, bands), the format matplotlib expects

print("shape of the piece read:", aerea.shape)

plt.figure(figsize=(7, 7))
plt.imshow(aerea)
plt.title("Crop read by window — notice the person in the middle of the field")
plt.axis("off")
plt.show()
dimensões da imagem completa: 15378 x 13484 (207 milhões de pixels)
shape do pedaço lido: (500, 500, 3)

Applying the blur only to the person’s region

To do this we need to: 1. Define the box (rows/columns) that covers the sensitive region; 2. Cut out only that piece of the array (image[y0:y1, x0:x1]); 3. Apply the Gaussian blur only to that crop; 4. Assign the result back to the same position in the original array.

The rest of the image never goes through the kernel, only our delimited region.

Code
# box (y0:y1, x0:x1) around the person, inside the 500x500 crop
y0, y1, x0, x1 = 170, 320, 130, 280

aerea_anonimizada = aerea.copy()
regiao = aerea_anonimizada[y0:y1, x0:x1]
regiao_borrada = cv2.GaussianBlur(regiao, ksize=(0, 0), sigmaX=15)
aerea_anonimizada[y0:y1, x0:x1] = regiao_borrada

fig, axes = plt.subplots(1, 2, figsize=(12, 6))
axes[0].imshow(aerea)
axes[0].add_patch(plt.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor="red", linewidth=2))
axes[0].set_title("Original (box = region we will blur)")
axes[1].imshow(aerea_anonimizada)
axes[1].set_title("Only the person's region was blurred")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Code
# close up, to make sure the person is unrecognizable
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].imshow(aerea[y0:y1, x0:x1])
axes[0].set_title("Before (close up)")
axes[1].imshow(aerea_anonimizada[y0:y1, x0:x1])
axes[1].set_title("After (close up)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

print(f"blurred pixels: {(y1 - y0) * (x1 - x0)} of {aerea.shape[0] * aerea.shape[1]} "
      f"({(y1 - y0) * (x1 - x0) / (aerea.shape[0] * aerea.shape[1]) * 100:.1f}% of the image)")

pixels borrados: 22500 de 250000 (9.0% da imagem)

Edge detection

As we’ve seen, kernels let us apply different properties to an image very simply and quickly. With kernels we can detect edges. There are two very famous kernels used for edge detection.

Sobel

An edge is, mathematically, a place where intensity changes abruptly. The Sobel filter is a kernel that approximates the image derivative (the “gradient”): one to detect horizontal changes, another for vertical ones. Where the gradient is large, there’s an edge.

Canny

Canny is the most widely used edge detector in practice. It does Sobel with extra steps: (1) blurs the image with a Gaussian blur to reduce noise, (2) computes the gradient (Sobel-like), (3) thins the edges down to 1 pixel wide, (4) uses two thresholds (one high, one low) to decide what is really an edge.

So it already “builds in” the lesson from the previous section: reducing noise with blur before looking for edges avoids detecting lots of false edges (texture/noise mistaken for real edges).

Code
sobel_edges = filters.sobel(gray_sk)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(gray_sk, cmap="gray")
axes[0].set_title("Grayscale")
axes[1].imshow(sobel_edges, cmap="gray")
axes[1].set_title("skimage.filters.sobel")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Code
# Canny directly on the original image vs. after a Gaussian blur
canny_sem_blur = cv2.Canny(gray_cv, threshold1=50, threshold2=150)

gray_borrado = cv2.GaussianBlur(gray_cv, ksize=(0, 0), sigmaX=0.8)
canny_com_blur = cv2.Canny(gray_borrado, threshold1=50, threshold2=150)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(canny_sem_blur, cmap="gray")
axes[0].set_title(f"Canny without blur ({(canny_sem_blur > 0).sum()} edge px)")
axes[1].imshow(canny_com_blur, cmap="gray")
axes[1].set_title(f"Canny with blur first (sigma=0.8) ({(canny_com_blur > 0).sum()} edge px)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()

Connected Component Analysis (CCA)

After turning an image into a binary one (black/white), the natural next step is to find out how many distinct objects there are and where they are. That’s what connected component analysis does: it groups white pixels that touch into a single numbered “blob”.

This is super useful in remote sensing, for example to count deforestation clearings, identify crop fields, isolate clouds, count buildings, etc.

We’ll binarize our image with Otsu (a method that picks the threshold automatically, without us having to guess a number) and run CCA on it.

Code
_, binary = cv2.threshold(gray_cv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
num_labels, labels_im, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)

print(f"components found (not counting the background): {num_labels - 1}")

fig, axes = plt.subplots(1, 3, figsize=(14, 5))
axes[0].imshow(gray_cv, cmap="gray")
axes[0].set_title("Grayscale")
axes[1].imshow(binary, cmap="gray")
axes[1].set_title("Binarized (Otsu threshold)")
axes[2].imshow(labels_im, cmap="nipy_spectral")
axes[2].set_title(f"{num_labels - 1} components (each color = 1 object)")
for ax in axes:
    ax.axis("off")
plt.tight_layout()
plt.show()
componentes encontrados (sem contar o fundo): 1420

Notice that we got a huge number of components. Most likely this is texture/noise turning into 1-2 pixel “objects”, not real objects. In practice, we almost always filter by minimum area to keep only the relevant components.

Code
area_minima = 50  # in pixels

labels_limpo = labels_im.copy()
for rotulo in range(1, num_labels):  # label 0 is the background, skip it
    if stats[rotulo, cv2.CC_STAT_AREA] < area_minima:
        labels_limpo[labels_limpo == rotulo] = 0

componentes_validos = [r for r in range(1, num_labels) if stats[r, cv2.CC_STAT_AREA] >= area_minima]
print(f"components before filtering: {num_labels - 1}  |  after (area >= {area_minima}px): {len(componentes_validos)}")

fig, ax = plt.subplots(figsize=(8, 5))
ax.imshow(gray_cv, cmap="gray")
ax.imshow(np.ma.masked_where(labels_limpo == 0, labels_limpo), cmap="nipy_spectral", alpha=0.7)
ax.set_title(f"{len(componentes_validos)} relevant components (area >= {area_minima} px)")
ax.axis("off")
plt.show()

# the 5 largest blobs: center and area
maiores = sorted(componentes_validos, key=lambda r: stats[r, cv2.CC_STAT_AREA], reverse=True)[:5]
for r in maiores:
    area = stats[r, cv2.CC_STAT_AREA]
    cx, cy = centroids[r]
    print(f"component {r}: area={area}px, center=({cx:.0f}, {cy:.0f})")
componentes antes do filtro: 1420  |  depois (área >= 50px): 50

componente 490: área=2508px, centro=(31, 156)
componente 3: área=1820px, centro=(37, 31)
componente 989: área=1007px, centro=(134, 206)
componente 1254: área=902px, centro=(70, 249)
componente 1012: área=811px, centro=(67, 201)

Preprocessing for neural networks

If you’ve seen (or will see) a convolutional neural network (CNN) being trained, the “data preparation” step literally is a bunch of the operations we just did:

What we did today Why it shows up before training a network
Resize Every CNN expects an input of fixed size (e.g. 224x224)
Brightness/contrast normalization Pixels as float32 between 0 and 1 (or standardized) train much better than raw uint8
Crop “Random crop” is a data augmentation technique: it cuts out random pieces so the network doesn’t memorize the exact position of objects
Blur / brightness / contrast Also used as augmentation: applying blur, randomly changing brightness, etc. during training teaches the network to be robust to these variations
Grayscale/channels Some architectures work with a single channel, others always expect 3: always check what your model expects

In practice, all of this comes packaged in libraries like torchvision.transforms and albumentations.

Code
def preprocess_para_cnn(imagem_rgb, tamanho=224):
    """Resize + normalization, the way a pre-trained CNN (e.g. ResNet) usually expects."""
    redimensionada = cv2.resize(imagem_rgb, (tamanho, tamanho), interpolation=cv2.INTER_AREA)
    tensor = redimensionada.astype("float32") / 255.0  # 0-255 -> 0.0-1.0

    # ImageNet means/stds — very common when using a model pre-trained on it
    media = np.array([0.485, 0.456, 0.406], dtype="float32")
    desvio = np.array([0.229, 0.224, 0.225], dtype="float32")
    tensor = (tensor - media) / desvio
    return tensor


tensor_final = preprocess_para_cnn(img)
print("shape final:", tensor_final.shape, "| dtype:", tensor_final.dtype)
print("mean per channel:", tensor_final.mean(axis=(0, 1)).round(3))
print("min/max:", round(float(tensor_final.min()), 2), round(float(tensor_final.max()), 2))
print()
print("all that's left: add the 'batch' dimension (making it (1, 224, 224, 3) or, in PyTorch, (1, 3, 224, 224))")
print("...and this could go straight into model.predict(...) / model(tensor)")
shape final: (224, 224, 3) | dtype: float32
média por canal: [-1.238  0.818  0.092]
min/max: -1.55 1.94

faltaria só: adicionar a dimensão de 'batch' (virar (1, 224, 224, 3) ou, no PyTorch, (1, 3, 224, 224))
...e isso já poderia entrar direto num model.predict(...) / model(tensor)

References