Module contents
Lesson 1 of 25Review 80 min

Review: images as signals, linear filters and edges

Review images as sampled signals, color conventions, classical linear filters, gradients, Gaussian scale space and handcrafted HOG and SIFT features before generalizing to learned CNN filters.

After this lesson you can

  • Represent images in H×W×C or C×H×W order, convert color conventions and normalize channels.
  • Apply box, Gaussian, Sobel and Laplacian filters and predict their effects from their kernels.
  • Calculate image gradients, magnitude and orientation and build a simple edge detector.
  • Build a Gaussian pyramid and explain scale space through the heat equation.
  • Describe the classical HOG and SIFT feature pipeline and what a CNN learns.

Before you start

An image before a CNN

A local average blurs an object’s boundary. A difference between neighbors instead responds precisely where intensity changes. Both procedures scan the same image with a small numerical template. Before learning those templates with a network, it helps to know what they can measure and what choices are hidden in boundary handling.

InteractivePaint a kernel

Correlation without reversing the kernel on a 32×32 geometric image: background 0.12, rectangle +0.45 and disk +0.35. Blue indicates positive values and orange negative; display intensity saturates at magnitude 1. Readouts and histogram use raw values.

Preparing images…

Manual weights are limited to [−10, 10]. With circular extension, sum 1 preserves the global mean. Replication and zero padding can change it; sum 0 cancels a constant image only when extension preserves that constant.

Kernel sum1.000
Raw minimum0.120
Raw maximum0.570
Raw mean0.245
Change the weights and compare the signed response, original image and their distributions.

In this lesson you will build local filters, gradients, scales and a classical descriptor. The next lesson generalizes the operation to batches, channels and learned filters. The question remains: what does each number passed to the next stage actually contain?

An image is a collection of samples

A digital image approximates a spatial signal with samples on a grid and quantizes their values. A color image can be stored as an H×W×CH\times W\times C or C×H×WC\times H\times W tensor; with batches these become NHWC and NCHW. Changing axis order with transpose does not change channels, but may return a noncontiguous view. Changing RGB to BGR does permute their meaning. Check shape and order before applying per-channel means or standard deviations.

With uint8, a channel usually represents integers from 0 to 255. To operate on a [0,1][0,1] scale, first convert to float and divide by 255. A derivative can be negative or exceed the input range: store it as float and decide later how to display it. Subtracting or filtering directly in an unsigned integer type can truncate or overflow the response. SciPy Sobel documentation warns that output uses the input dtype by default.

In RGB, a weighted combination can give a useful brightness representation; its coefficients and range depend on the color convention. Do not confuse luma calculated on encoded RGB with linear physical luminance without undoing the corresponding transfer function. YUV and YCbCr do not designate one universal matrix and range: state which transform you use.

For example, ITU-R BT.601 uses coefficients 0.299, 0.587 and 0.114 for luma Y′Y' of nonlinear RGB signals. The next cell also defines two full-range color differences and inverts them; this is an explicit teaching convention, not the complete limited-range digital encoding of BT.601. Also check axes, BGR and per-channel normalization without losing the original image.

[ ]Axes, channels and colorBrowser
import numpy as np

# Dos imágenes pequeñas en NHWC, con RGB codificado en uint8.
rgb_u8=np.array([[[[255,0,0],[0,255,0]],[[0,0,255],[255,255,255]]],
                 [[[0,0,0],[128,64,32]],[[32,128,64],[64,32,128]]]],dtype=np.uint8)
rgb=rgb_u8.astype(np.float64)/255
nchw=np.transpose(rgb,(0,3,1,2))
assert np.array_equal(np.transpose(nchw,(0,2,3,1)),rgb)
bgr=rgb[...,::-1]
assert np.array_equal(bgr[...,::-1],rgb)
mean=np.array([.5,.5,.5]);std=np.array([.25,.2,.4])
standard=(rgb-mean)/std
assert np.allclose(standard*std+mean,rgb)
r,g,b=np.moveaxis(rgb,-1,0)
y=.299*r+.587*g+.114*b
cb=(b-y)/1.772+.5;cr=(r-y)/1.402+.5
restored_r=y+1.402*(cr-.5);restored_b=y+1.772*(cb-.5)
restored_g=(y-.299*restored_r-.114*restored_b)/.587
restored=np.stack([restored_r,restored_g,restored_b],axis=-1)
print('NHWC:',rgb.shape,'NCHW:',nchw.shape,'vista compartida:',np.shares_memory(rgb,nchw))
print('Y, Cb, Cr de rojo:',y[0,0,0],cb[0,0,0],cr[0,0,0])
print('Error máximo de ida y vuelta:',np.max(np.abs(restored-rgb)))
assert np.allclose(restored,rgb)

One template, two operations

In linear image filtering, combine a neighborhood of II with a kernel KK. Here we use correlation for an odd-sized kernel, with rr and ss measured from its center:

(K⋆I)[y,x]=∑r,sK[r,s]I[y+r,x+s].(K\star I)[y,x]=\sum_{r,s}K[r,s]I[y+r,x+s].

Mathematical convolution reverses the signs of both offsets, equivalent to flipping the kernel before correlation. Layers in many deep-learning libraries call correlation without reversal convolution; in discrete convolution we examine both conventions in detail. With a symmetric kernel they agree; with Sobel the sign changes. The MIT vision book filtering chapter distinguishes the operations and the role of image extension.

At boundaries you must decide what lies outside: zeros, repetition, reflection or a periodic image. This choice is part of the operation. If ∑K=1\sum K=1, the filter preserves a constant input where its extension is also constant. Zero padding can darken its margins and change the global mean. Circular convolution with sum one does preserve the global sum. If ∑K=0\sum K=0, a constant vanishes under an extension that preserves it; zeros outside can introduce artificial boundary responses. The figure’s histogram is calculated on responses, not colors clipped for display.

A box kernel averages equal weights. A Gaussian gives nearby neighbors more weight. Both smooth, but their frequency responses differ. A sharpening kernel adds a high-frequency component to the original image; a discrete Laplacian detects slope changes and sums to zero. Sum, symmetry and sign distribution are clues, not a complete description of an arbitrary filter.

Separating two dimensions

A kernel KK is separable if it can be written as an outer product K=uv⊤K=uv^\top. A horizontal filter can be applied first and then a vertical one. A nonzero kernel is separable if and only if its matrix has rank one; the zero kernel is also separable, with rank zero. For a k×kk\times k kernel, direct calculation uses k2k^2 products per pixel and two separable passes use 2k2k, excluding boundaries and optimizations.

The continuous isotropic Gaussian factorizes because

exp⁡ ⁣(−x2+y22σ2)=exp⁡ ⁣(−x22σ2)exp⁡ ⁣(−y22σ2).\exp\!\left(-\frac{x^2+y^2}{2\sigma^2}\right) =\exp\!\left(-\frac{x^2}{2\sigma^2}\right) \exp\!\left(-\frac{y^2}{2\sigma^2}\right).

Sampling both factors in a rectangular window and normalizing consistently also yields a discrete outer product. A different window, boundaries and precision can change other details. The lab compares direct calculation with two passes instead of assuming they agree for every padding.

Gradient: magnitude, orientation and sign

The image gradient combines horizontal and vertical derivatives. For a discrete image we can estimate them with Sobel: a central difference in one direction and weighted average in the other. With correlation and rows increasing downward, take

Kx=18[−101−202−101],Ky=Kx⊤.K_x=\frac18\begin{bmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{bmatrix}, \qquad K_y=K_x^\top.

The 1/81/8 normalization makes an interior ramp increasing one unit per column have gx=1g_x=1. Other implementations omit that constant; adjust the threshold when comparing. Calculate M=gx2+gy2M=\sqrt{g_x^2+g_y^2} and θ=atan2⁡(gy,gx)\theta=\operatorname{atan2}(g_y,g_x). The gradient points toward increasing intensity and is normal to a level contour; the edge tangent direction is rotated 90°. In a flat region, M=0M=0 and orientation is undefined.

InteractiveThe gradient field

Geometric image with reproducible uniform noise, seed 1601. Sobel is correlation normalized by 8; Gaussian smoothing is truncated at 3σ and replicates the border. One in four positions per axis is drawn.

Preparing field…

Blue intensity represents fixed range [−0.03, 0.72], including after smoothing. Each orange arrow points toward increasing intensity and has length proportional to magnitude; the gradient is normal to the edge. x increases rightward and y rows downward. The threshold selects arrows without changing derivatives or RMS.

0.0
0.06
Magnitude RMS across 1024 pixels0.1060
Visible arrows30/64
Adjust smoothing and threshold; arrows indicate gradients on the same image.

Scharr changes weights to improve rotational symmetry of the discrete approximation. With the same correlation convention and unit-ramp normalization, its horizontal kernel is

KxScharr=132[−303−10010−303].K_x^{\mathrm{Scharr}}=\frac1{32}\begin{bmatrix}-3&0&3\\-10&0&10\\-3&0&3\end{bmatrix}.

A second derivative, such as the Laplacian, responds to local curvature and can change sign on both sides of an edge. In the continuous domain, under assumptions permitting differentiation and convolution to be exchanged, Δ(Gσ∗I)=(ΔGσ)∗I\Delta(G_\sigma*I)=(\Delta G_\sigma)*I: the right side applies a Laplacian of Gaussian. Its zero crossings differ from gradient magnitude and need a contrast criterion to avoid marking noise. In a finite padded image, separately check discretization and boundary effects. Prior smoothing reduces some noise but can also erase details and shift or merge responses: compare the figure with and without smoothing before choosing a scale.

To turn responses into thin contours, Canny combines smoothing, derivatives, non-maximum suppression along the gradient and hysteresis thresholds. A weak point is retained if it belongs to a chain connected to a strong point; thresholding MM once is insufficient. Canny formulated detection, localization and single-response criteria and describes the tradeoff. The code exercise implements a thresholded Sobel detector, not the complete Canny algorithm.

Scales, heat and resampling

Gaussian scale space considers L(x,y,σ)=Gσ∗IL(x,y,\sigma)=G_\sigma*I, with normalized GσG_\sigma. In R2\mathbb R^2, for a continuous bounded initial image II, the solution of ∂tu=Δu\partial_t u=\Delta u that remains bounded on every finite time interval is u(⋅,t)=G2t∗Iu(\cdot,t)=G_{\sqrt{2t}}*I for t>0t>0. Increasing σ\sigma corresponds to allowing more diffusion time.

In the infinite continuous domain, two Gaussian smoothings with deviations σ1\sigma_1 and σ2\sigma_2 equal one with deviation σ12+σ22\sqrt{\sigma_1^2+\sigma_2^2}. In our pyramid, each prefilter uses σ=1\sigma=1 measured in pixels of its level before halving it. Nominal accumulated variance in original pixels through level nn is σ2∑k=0n−14k\sigma^2\sum_{k=0}^{n-1}4^k, because each pixel at level kk spans 2k2^k original pixels. This reference is not an exact scale for the discrete result: truncation, boundaries and possible aliasing prevent directly applying the continuous semigroup. The lab records this reference and each level’s shape. A Laplacian pyramid stores differences that allow reconstruction together with the coarsest level, provided the same expansion rule is used and dimensions are preserved.

InteractiveMoving through scale space

A periodic cosine texture of frequency 26/64 cycles per pixel is decimated by taking even samples. Images share origin and intensity scale: the discrete Gaussian filter is normalized, truncated at 3σ and uses circular extension.

Preparing scales…

The observed frequency after the first reduction folds to 0.1875 cycles per new sample. The displayed response preserves sign: its magnitude gives attenuation and, when negative, reverses phase. Smoothing does not guarantee elimination of aliasing for every signal. The second level applies the same local σ on its own grid before decimation; it is not the accumulated scale in original pixels.

1.0
Before decimation
Original frequency (cycles/pixel)0.40625
Alias after first step0.1875 cycles/sample
First filter response0.03962
Pyramid dimensions64→32→16 samples
Compare subsampling with and without prefiltering on a texture of known frequency.

When keeping every second sample, the new Nyquist frequency is half the previous one. Components above that limit can be confused with lower frequencies and generate moiré. A prefilter must attenuate those components sufficiently for the signal and error tolerance of interest. A finite Gaussian reduces aliasing but does not exactly eliminate all out-of-band energy. If we require preserving a nontrivial passband and exactly eliminating a whole interval of high frequencies, a nonzero FIR filter cannot do it; the ideal strict-cutoff filter has infinite support. The zero filter removes all signal but retains no useful information. In sampling and aliasing you can follow the spectral replicas explaining this observation.

From designed filters to learned filters

A Gabor function multiplies a Gaussian envelope by an oriented sinusoidal oscillation. For example, g(x,y)=exp⁡[−(x2+y2)/(2s2)]cos⁡[2πf(xcos⁡θ+ysin⁡θ)]g(x,y)=\exp[-(x^2+y^2)/(2s^2)]\cos[2\pi f(x\cos\theta+y\sin\theta)], with scale s>0s>0, frequency ff and oscillation orientation θ\theta. Its response depends on these parameters, so a filter bank can capture texture and edges in several directions. Hubel and Wiesel observed orientation-selective responses in cat visual cortex. That observation inspires analogies about local fields and hierarchies, but does not prove that a CNN reproduces brain function or that each biological neuron is exactly a Gabor filter.

In a handcrafted feature pipeline, first choose a representation and then fit a classifier. HOG accumulates gradient orientations in cells, normalizes blocks of cells and feeds, for example, a linear SVM. In the pedestrian study by Dalal and Triggs, the reference configuration uses a 64×128 window, 8×8 cells, blocks of 2×2 cells and 9 unsigned orientation bins. Those dimensions belong to that detector, not the small digits in the lab.

SIFT finds points in scale space, estimates their location and orientation and forms a local descriptor. Lowe uses 4×4 histograms of 8 orientations in experiments, or 128 components per point. The desired invariance has limits under perspective changes, discretization, noise and occlusion. A CNN learns filters and combinations from data but still incorporates choices of architecture, sampling and training.

Labs

First build a correlation library and compare it with SciPy, specifying boundary extension. Then compute a simplified HOG and fit an SVM to scikit-learn digits. Its images are 8×8, with 10 classes, 1797 examples and values from 0 to 16, according to the dataset documentation. Select on validation and hold test until the end; do not confuse this measurement with the pedestrian paper’s.

Cells retain state and must be run in order. Printed times describe that particular Pyodide run; vectorization and a window view do not alone guarantee an operation is faster in every environment.

The lab descriptor uses four 4×4-pixel cells, 9 unsigned bins and one normalized block of 36 components; it does not interpolate votes between bins or reproduce the pedestrian detector window. One run of the cells, with 1078 training, 359 validation and 360 test images, selected α=0,0001\alpha=0,0001 with validation accuracy 0.78273 and achieved 0.86667 on final test. This measures that split and protocol, not guaranteed performance. Changing the method after looking at test would turn that result into part of tuning.

[ ]Filters from scratchBrowser
import numpy as np
from scipy import ndimage
from numpy.lib.stride_tricks import sliding_window_view
from time import perf_counter

def _filter_inputs(image, kernel, padding):
    image = np.asarray(image, dtype=np.float64)
    kernel = np.asarray(kernel, dtype=np.float64)
    if image.ndim != 2 or not image.size or kernel.ndim != 2 or not kernel.size:
        raise ValueError('Se esperan imagen y núcleo bidimensionales no vacíos')
    if any(size % 2 == 0 for size in kernel.shape):
        raise ValueError('El núcleo debe tener dimensiones impares')
    if not np.isfinite(image).all() or not np.isfinite(kernel).all():
        raise ValueError('Imagen y núcleo deben ser finitos')
    modes = {'reflect': 'symmetric', 'nearest': 'edge', 'zero': 'constant', 'wrap': 'wrap'}
    if padding not in modes:
        raise ValueError('Extensión desconocida')
    a, b = (size // 2 for size in kernel.shape)
    padded = np.pad(image, ((a, a), (b, b)), mode=modes[padding])
    return image, kernel, padded

def correlate_loop(image, kernel, padding='reflect'):
    image, kernel, padded = _filter_inputs(image, kernel, padding)
    out = np.empty_like(image)
    h, w = kernel.shape
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            out[i, j] = np.sum(padded[i:i+h, j:j+w] * kernel)
    return out

def correlate_window(image, kernel, padding='reflect'):
    _, kernel, padded = _filter_inputs(image, kernel, padding)
    windows = sliding_window_view(padded, kernel.shape)
    return np.einsum('ijab,ab->ij', windows, kernel, optimize=False)

def gaussian_1d(sigma, radius=None):
    if not np.isfinite(sigma) or not 0 <= sigma <= 10:
        raise ValueError('sigma debe ser finito y estar entre 0 y 10')
    if sigma == 0:
        return np.array([1.])
    if radius is None:
        radius = int(np.ceil(3*sigma))
    if not isinstance(radius, (int, np.integer)) or isinstance(radius, (bool, np.bool_)) or not 0 <= radius <= 30:
        raise ValueError('radio debe ser un entero entre 0 y 30')
    coordinates = np.arange(-radius, radius+1, dtype=float)
    with np.errstate(over='ignore', under='ignore'):
        weights = np.exp(-.5*(coordinates/sigma)**2)
    return weights / weights.sum()

def gaussian_filter_separable(image, sigma, padding='reflect'):
    g = gaussian_1d(sigma)
    return correlate_window(correlate_window(image, g[None, :], padding), g[:, None], padding)

SOBEL_X = np.array([[-1.,0.,1.],[-2.,0.,2.],[-1.,0.,1.]])/8
SOBEL_Y = SOBEL_X.T

def sobel(image, sigma=0, padding='reflect'):
    smooth = gaussian_filter_separable(image, sigma, padding)
    gx = correlate_window(smooth, SOBEL_X, padding)
    gy = correlate_window(smooth, SOBEL_Y, padding)
    return gx, gy, np.hypot(gx, gy), np.arctan2(gy, gx)

def gaussian_pyramid(image, levels, sigma=1.):
    if not isinstance(levels, int) or isinstance(levels, bool) or levels < 1:
        raise ValueError('levels debe ser un entero positivo')
    current = np.asarray(image, dtype=float)
    pyramid = [current]
    for _ in range(levels-1):
        current = gaussian_filter_separable(current, sigma)[::2, ::2]
        pyramid.append(current)
    return pyramid

def expand_level(coarse, target_shape, sigma=.5):
    """Repetir vecinos, recortar al tamaño anterior y suavizar con reflect."""
    coarse = np.asarray(coarse, dtype=float)
    if coarse.ndim != 2 or not coarse.size or len(target_shape) != 2:
        raise ValueError('Se esperan imagen 2D y forma objetivo 2D')
    if any(t not in (2*c-1, 2*c) for t, c in zip(target_shape, coarse.shape)):
        raise ValueError('La forma objetivo no corresponde a una decimación por dos')
    expanded = np.repeat(np.repeat(coarse, 2, axis=0), 2, axis=1)
    expanded = expanded[:target_shape[0], :target_shape[1]]
    return gaussian_filter_separable(expanded, sigma)

def laplacian_pyramid(gaussian_levels):
    if not gaussian_levels:
        raise ValueError('La pirámide debe tener al menos un nivel')
    residuals = [fine - expand_level(coarse, fine.shape)
                 for fine, coarse in zip(gaussian_levels[:-1], gaussian_levels[1:])]
    return residuals, gaussian_levels[-1].copy()

def reconstruct_pyramid(residuals, coarse):
    image = np.asarray(coarse, dtype=float).copy()
    for residual in reversed(residuals):
        image = expand_level(image, residual.shape) + residual
    return image

print('Correlación: float64, padding reflect a media muestra y núcleos impares.')
[ ]Compare filters and timesBrowser
rng = np.random.default_rng(16001)
image = rng.normal(size=(28, 31))
kernel = rng.normal(size=(3, 5))
scipy_modes = {'reflect':'reflect', 'nearest':'nearest', 'zero':'constant', 'wrap':'grid-wrap'}
for mode, scipy_mode in scipy_modes.items():
    a = correlate_loop(image, kernel, mode)
    b = correlate_window(image, kernel, mode)
    c = ndimage.correlate(image, kernel, mode=scipy_mode, cval=0.)
    assert np.allclose(a, b, atol=1e-12)
    assert np.allclose(b, c, atol=1e-12)
    print(mode, 'error máximo frente a SciPy:', np.max(np.abs(b-c)))

one = np.ones((3, 3))
box = np.ones((3, 3))/9
assert np.allclose(correlate_window(one, box, 'reflect'), 1)
zero_mean = correlate_window(one, box, 'zero').mean()
assert np.isclose(zero_mean, 49/81)
print('Media de imagen constante con padding cero:', zero_mean)

ramp = np.tile(np.arange(12), (8, 1))
gx, gy, _, _ = sobel(ramp)
assert np.allclose(gx[1:-1, 1:-1], 1)
assert np.allclose(gy[1:-1, 1:-1], 0)
print('Rampa horizontal: Sobel x interior =', gx[3, 3], '; Sobel y =', gy[3, 3])

impulse = np.zeros((11, 11)); impulse[5, 5] = 1
gauss = gaussian_1d(1.)
assert np.allclose(gaussian_filter_separable(impulse, 1.), correlate_window(impulse, np.outer(gauss,gauss)))
assert np.allclose(gaussian_filter_separable(image, 0), image)
assert np.array_equal(gaussian_1d(1e-200), [0., 1., 0.])
for bad_sigma in (11., float('inf'), float('nan')):
    try:
        gaussian_1d(bad_sigma)
        raise AssertionError('Un sigma inválido fue aceptado')
    except ValueError:
        pass
for bad in (np.array([]), np.full((2,2), np.nan)):
    try:
        correlate_window(bad, box)
        raise AssertionError('Una entrada inválida fue aceptada')
    except ValueError:
        pass
print('Impulso, separabilidad, identidad y entradas inválidas: comprobados')
[ ]Gaussian and Laplacian pyramidsBrowser
test_image = np.random.default_rng(16002).normal(size=(64, 64))
kernel = np.outer(gaussian_1d(1.), gaussian_1d(1.))
times = {}
for label, fn in [('bucles', correlate_loop), ('ventana', correlate_window)]:
    start = perf_counter(); result = fn(test_image, kernel); times[label] = perf_counter()-start
start = perf_counter(); reference = ndimage.correlate(test_image, kernel, mode='reflect'); times['SciPy'] = perf_counter()-start
assert np.allclose(result, reference)
print('Tiempos de esta ejecución, segundos:', times)
print('Las temporizaciones dependen del entorno y no garantizan un ganador.')
levels = gaussian_pyramid(test_image, 4, sigma=1.)
print('Formas de la pirámide:', [a.shape for a in levels])
sigma_local = 1.
nominal_variances = [sigma_local**2 * sum(4**k for k in range(n)) for n in range(len(levels))]
print('Varianza nominal acumulada en píxeles originales:', nominal_variances)
print('Desviación nominal acumulada en píxeles originales:', np.sqrt(nominal_variances))
assert nominal_variances == [0., 1., 5., 21.]
for shape in ((64, 64), (63, 65)):
    image = np.random.default_rng(16003).normal(size=shape)
    levels = gaussian_pyramid(image, 4, sigma=1.)
    residuals, coarse = laplacian_pyramid(levels)
    reconstructed = reconstruct_pyramid(residuals, coarse)
    error = np.max(np.abs(reconstructed-image))
    assert np.allclose(reconstructed, image, atol=1e-12)
    print('Pirámide laplaciana', shape, 'formas:', [a.shape for a in levels], 'error máximo de reconstrucción:', error)
print('Expansión: repetir vecinos, recortar al tamaño anterior y suavizar; residual = fino − expansión.')

frequency = .4
n = np.arange(80)
signal = np.cos(2*np.pi*frequency*n)
decimated = signal[::2]
aliased = np.cos(2*np.pi*.2*np.arange(len(decimated)))
print('Error de alias sin filtrar:', np.max(np.abs(decimated-aliased)))
print('Ganancia de media de dos muestras a 0,4 ciclos/píxel:', abs(np.cos(np.pi*frequency)))
[ ]Data and splitsBrowser
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

digits = load_digits()
images = digits.images.astype(np.float64)/16.
labels = digits.target.astype(int)
ids = np.arange(len(labels))
train_ids, rest_ids = train_test_split(ids, test_size=.4, random_state=16001, stratify=labels)
valid_ids, test_ids = train_test_split(rest_ids, test_size=.5, random_state=16002, stratify=labels[rest_ids])
assert len(set(train_ids) & set(valid_ids)) == 0
assert len(set(train_ids) & set(test_ids)) == 0
assert len(set(valid_ids) & set(test_ids)) == 0
print('Digits:', images.shape, 'rango original 0 a 16, 10 clases')
print('Partición estratificada train/validación/test:', len(train_ids), len(valid_ids), len(test_ids))
print('Semillas de partición: 16001 y 16002; test se consulta una sola vez al final.')
[ ]Simplified HOGBrowser
def hog_digits(images):
    """HOG simplificado: 2×2 celdas de 4×4, 9 bins sin signo, un bloque 2×2."""
    images = np.asarray(images, dtype=np.float64)
    if images.ndim != 3 or images.shape[1:] != (8, 8) or not np.isfinite(images).all():
        raise ValueError('Se espera un lote finito de imágenes 8×8')
    padded = np.pad(images, ((0,0),(1,1),(1,1)), mode='symmetric')
    gx = (padded[:,1:-1,2:] - padded[:,1:-1,:-2]) / 2
    gy = (padded[:,2:,1:-1] - padded[:,:-2,1:-1]) / 2
    magnitude = np.hypot(gx, gy)
    angle = np.mod(np.arctan2(gy, gx), np.pi)
    bins = np.minimum((angle * (9/np.pi)).astype(int), 8)
    masks = bins[..., None] == np.arange(9)
    votes = magnitude[..., None] * masks
    cells = votes.reshape(-1, 2, 4, 2, 4, 9).sum(axis=(2,4))
    block = cells.reshape(-1, 36)
    eps = 1e-6
    block = block/np.sqrt(np.sum(block**2, axis=1, keepdims=True) + eps**2)
    block = np.minimum(block, .2)
    return block/np.sqrt(np.sum(block**2, axis=1, keepdims=True) + eps**2)

X_hog = hog_digits(images)
assert X_hog.shape == (len(images), 36)
assert np.allclose(hog_digits(np.ones((1, 8, 8))), 0.)
print('HOG simplificado:', X_hog.shape, '; sin interpolación de bins')
print('Bloque 2×2, 9 bins sin signo, normalización L2, recorte 0,2 y nueva L2.')
[ ]Train HOG candidatesBrowser
classifier_a = SGDClassifier(loss='hinge', alpha=.001, random_state=16003, max_iter=1000, tol=1e-3)
classifier_a.fit(X_hog[train_ids], labels[train_ids])
valid_a = accuracy_score(labels[valid_ids], classifier_a.predict(X_hog[valid_ids]))
print('SVM lineal con SGD, alpha 0,001: exactitud en validación =', valid_a)
[ ]Select by validationBrowser
classifier_b = SGDClassifier(loss='hinge', alpha=.0001, random_state=16003, max_iter=1000, tol=1e-3)
classifier_b.fit(X_hog[train_ids], labels[train_ids])
valid_b = accuracy_score(labels[valid_ids], classifier_b.predict(X_hog[valid_ids]))
print('SVM lineal con SGD, alpha 0,0001: exactitud en validación =', valid_b)
[ ]Final evaluationBrowser
best_alpha = .001 if valid_a >= valid_b else .0001
train_and_valid = np.concatenate([train_ids, valid_ids])
final_classifier = SGDClassifier(loss='hinge', alpha=best_alpha, random_state=16003, max_iter=1000, tol=1e-3)
final_classifier.fit(X_hog[train_and_valid], labels[train_and_valid])
test_pred = final_classifier.predict(X_hog[test_ids])
test_accuracy = accuracy_score(labels[test_ids], test_pred)
print('Alpha seleccionado solo con validación:', best_alpha)
print('Exactitud de test, evaluación única:', test_accuracy)
print('Matriz de confusión; filas reales y columnas predichas:')
print(confusion_matrix(labels[test_ids], test_pred, labels=np.arange(10)))

Keep the stated protocol and split. When building LeNet, an accuracy comparison needs the same examples and evaluation criterion; state any preprocessing change. Repeated selection from test invalidates its role as independent evaluation.

Exercises

QuizFour templates
A is a normalized 3×3 box; B is this lesson's Sobel x; C has center 5, axial neighbors −1 and corners 0; D has center −4, axial neighbors 1 and corners 0. Which identification is correct?
NumericDirect cost
How many multiplications per pixel are required to apply a dense 15×15 kernel directly? Exclude additions and optimizations.
NumericTwo passes
If that 15×15 kernel is separable, how many multiplications per pixel do two dense passes of 15 coefficients use?
ProofSeparability and rank
Prove: Characterize exactly when a matrix kernel is separable.
0
A kernel is separable if vectors u and v exist such that K=uvᵀ; K may be the zero matrix.

Step 1 of 3. What rank can an outer product have?

CodeSobel with orientation
Implement sobel_edges(img, sigma, threshold). Accept a nonempty finite real 2D array, finite sigma between 0 and 3 and finite nonnegative threshold; reject invalid inputs or nonfinite computations with ValueError. Convert to float. If sigma>0, filter separably using the normalized discrete Gaussian on [−r,r], r=ceil(3·sigma); if sigma=0 do not smooth. Use symmetric extension including the boundary pixel, correlation with Kx=[[-1,0,1],[-2,0,2],[-1,0,1]]/8 and Ky=Kxᵀ. Return (edges, orientation): edges is M>threshold; orientation contains 0, 45, 90 or 135 degrees, rounding atan2(gy,gx) to the nearest multiple of 45° modulo 180°, and −1 where M=0. Rows increase downward. Do not implement hysteresis or non-maximum suppression.
import numpy as np

def sobel_edges(img, sigma, threshold):
  pass
Shift+Enter to run
QuizFilter before downsampling
You will retain every second sample of a high-frequency texture. What ideally prevents aliasing while preserving a useful band, and what happens in a finite implementation?
[ ]Check exercise calculationsBrowser
import numpy as np

print('Productos por píxel, directo:', 15**2, '; separable:', 2*15)
print('Rango del núcleo nulo:', np.linalg.matrix_rank(np.zeros((3, 3))))
scharr = np.array([[-3, 0, 3], [-10, 0, 10], [-3, 0, 3]]) / 32
rampa = np.tile(np.arange(3), (3, 1))
print('Respuesta de Scharr a la rampa unitaria:', np.sum(scharr * rampa))

References