Skip to content

Images as tensors: pixels, channels, resizing and honest splits

What a vision model actually receives — a grid of numbers with a stated layout, range and size — and the three places it goes wrong before any training starts: layout, resizing and splits.

Introductory ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Describe an image as a height × width × channel array with a stated range
  • Spot a channel-order or color-order mix-up from its symptoms
  • Choose between stretching, cropping and letterboxing when resizing
  • Split image data by source before cropping or augmenting

Read first

01

A grid of numbers

Read

A color photo is three stacked grids: red, green and blue, one number per pixel. Files store 8-bit values from 0 to 255; models usually want them scaled to 0–1 and then centered with each channel's mean and spread from the pretraining data.

So an image is a tensorMedia tensorAn image or sound decoded into numbers (pixels or samples) the same way every time, cached by the file's content. with a shape, a range and an order. A 224 × 224 color image is 224 × 224 × 3 numbers in NumPy and image files, but 3 × 224 × 224 in PyTorch (channel orderChannel order (HWC and CHW)Where the color axis sits in an image array: height × width × channels (files, NumPy) or channels first (PyTorch).). Some libraries also read colors as BGR instead of RGB. A wrong order still runs; it shows the network a different picture.

02

What a folder really holds

Read

Before any model, profile the collection. CodeSplash links image files in place and reads them the same way every time:

Image collection profile (size, color, sharpness, duplicates)Recorded · Python and R agreeRecorded 2026-11-25 · 41 values compared
R

22 images: median 62 × 48 px; 1 dark, 1 bright, 2 blurry, 3 in near-duplicate groups.

Images read
22
Mean brightness
0.5090
Median sharpness
697.19
In duplicate groups
3

Plots

Brightness and sharpnessWhich images are too dark, washed out, blurry or duplicated?
View data
Brightness (0–1)FlagFileSharpness (variance of the Laplacian)
0.5459OKgradient_a.png111.35
0.5459Duplicategradient_a_copy.png111.35
0.5458Duplicategradient_a_near.png138.60
0.3877OKgradient_b.png111.66
0.5002OKstripes_fine.png22408.52
0.5002OKstripes_blurred.png427.86
0.5964OKstripes_wide.png4403.90
0.5294OKchecker.png35891.72
0.5096OKchecker_gray.png27468.42
0.2080OKchecker_alpha.png966.52
0.2885Blurrypalette.png73.680
0.0469Darkdark.png73.171
0.9604Brightbright.png73.887
0.5020Blurryflat_mid.png0
0.5971OKportrait.png201.51
0.5170OKwide_banner.png2909.27
0.5925OKphoto_a.jpg1481.37
0.5011OKphoto_b.jpg8914.04
0.4901OKphoto_c.jpg10461.76
0.8435OKplain.jpg230.68
0.4903OKgray.jpg18698.44
0.5003OKstripes_fine_copy.jpg22509.03
Pixel sizesAre the images a consistent size and shape, or a mix of resolutions and orientations?
View data
FormatHeight (px)FileWidth (px)
PNG48gradient_a.png64
PNG48gradient_a_copy.png64
PNG48gradient_a_near.png64
PNG40gradient_b.png80
PNG64stripes_fine.png64
PNG64stripes_blurred.png64
PNG50stripes_wide.png90
PNG60checker.png60
PNG32checker_gray.png48
PNG40checker_alpha.png40
PNG36palette.png36
PNG40dark.png60
PNG40bright.png60
PNG30flat_mid.png30
PNG90portrait.png40
PNG20wide_banner.png120
JPEG48photo_a.jpg64
JPEG56photo_b.jpg56
JPEG48photo_c.jpg72
JPEG40plain.jpg40
JPEG48gray.jpg48
JPEG64stripes_fine_copy.jpg64
Images by similarity (classic features)Which rows group together, and how well separated are the groups?
View data
FlagFilePC 1PC 2
OKgradient_a.png0.70912.310
Duplicategradient_a_copy.png0.70912.310
Duplicategradient_a_near.png0.70962.295
OKgradient_b.png−2.8340.6196
OKstripes_fine.png−0.0566−1.913
OKstripes_blurred.png−0.1064−1.341
OKstripes_wide.png1.9540.8558
OKchecker.png0.6090−1.846
OKchecker_gray.png0.1656−1.966
OKchecker_alpha.png−6.8330.3521
Blurrypalette.png−5.2692.574
Darkdark.png−10.389−1.554
Brightbright.png10.204−0.4908
Blurryflat_mid.png−0.1527−1.524
OKportrait.png2.2442.898
OKwide_banner.png−0.33540.6315
OKphoto_a.jpg1.7661.773
OKphoto_b.jpg−0.2190−0.4322
OKphoto_c.jpg−0.2570−0.5075
OKplain.jpg7.662−1.198
OKgray.jpg−0.2377−1.765
OKstripes_fine_copy.jpg−0.0436−2.080

Assumptions

  • PNG, JPEG and TIFF — 1 listed files are not PNG, JPEG or a readable kind of TIFF.
  • Sharpness depends on size and content — Sharpness is measured at most 512 pixels on the long side; plain images score low without being blurred.
  • Personal data in metadata — 1 images carry GPS location data (coordinates are not read).

Flagged images

FileFlagBrightnessSharpnessDuplicate group
gradient_a_copy.pngDuplicate0.5459111.351
gradient_a_near.pngDuplicate0.5458138.601
palette.pngBlurry0.288573.6800
dark.pngDark0.046973.1710
bright.pngBright0.960473.8870
flat_mid.pngBlurry0.502000

Cameras (EXIF)

Make and modelImages
Fixturecam FX-1001
Fixturecam FX-2001
Othercam O-11
  • 1 rows have no path and are left out.
  • 1 rows point to files that do not exist and are left out.
  • 1 rows are not PNG, JPEG or a readable kind of TIFF and are left out.
  • 1 rows could not be decoded and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Image collection profile (size, color, sharpness, duplicates)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.images 1.1.0 · spec bcdfced43aa2ed60
# Dataset: ml_images (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Images listed in the path column
PATH <- "path"
LABEL <- NULL
FOLDER <- path.expand("")
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/ml_images.parquet", mustWork = FALSE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_images.parquet", col_select = c(PATH, LABEL)))
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"original\",\"formats\":[\"tiff\"],\"mode\":\"rgb\",\"normalize\":\"none\",\"orientation\":\"stored\",\"size\":[224,224]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/describe.images/folder_defaults/out-r", df,
                        "tests/parity/fixtures/ml_images.parquet")
media_ids <- cs_media_ids(media, df)
MAX_SIDE <- 512
warnings <- list()
status <- character(0); info <- list(); feats <- list(); hashes <- list()
nz <- function(x) !is.null(x) && !is.na(x) && nzchar(x)
for (i in seq_len(nrow(df))) {
  path <- cs_img_resolve(as.character(df[[PATH]][i]), FOLDER, DATA_DIR)
  if (is.na(path)) { status <- c(status, "no path"); info[[i]] <- list(row = i - 1L); next }
  r <- cs_img_read(path)
  if (r$status == "unsupported" && cs_img_is_tiff(path))  # TIFF: decoded by the host
    r <- cs_img_tiff_read(path, r, media, if (is.null(media_ids)) NA_character_ else media_ids[i])
  status <- c(status, r$status)
  rec <- list(row = i - 1L, path = path, file = basename(path), format = r$format, bytes = r$bytes, md5 = r$md5)
  if (r$status == "ok") {
    small <- cs_img_fit(r$rgb, MAX_SIDE)
    m <- cs_img_measures(small)
    h <- cs_img_phash(cs_img_luma(small))
    rec <- c(rec, list(width = r$width, height = r$height, alpha = r$alpha, phash = cs_img_hex(h)), m,
             if (identical(r$format, "TIFF")) cs_img_tiff_exif(path) else cs_img_exif(path))
    feats[[length(feats) + 1]] <- c(m$brightness, m$contrast, m$mean_r, m$mean_g, m$mean_b, m$colourfulness, m$saturation,
                                    if (is.nan(m$sharpness)) NA else log1p(m$sharpness), m$entropy, cs_img_thumb(small))
    hashes[[length(hashes) + 1]] <- h
  }
  info[[i]] <- rec
}
ok <- which(status == "ok")
if (!length(ok)) {
  if (!length(status)) cs_error("CS_E_NO_ROWS")
  if (all(status == "no path")) cs_error("CS_E_ALL_MISSING", column = PATH)
  # None of the listed files could be read (missing, not PNG, JPEG or TIFF, or not decodable).
  cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "a PNG, JPEG or TIFF file that exists",
           count = sum(status != "no path"))
}
for (pair in list(c("no path", "have no path"), c("missing", "point to files that do not exist"), c("unsupported", "are not PNG, JPEG or a readable kind of TIFF"), c("unreadable", "could not be decoded"))) {
  k <- sum(status == pair[1])
  if (k) warnings <- c(warnings, sprintf("%d rows %s and are left out.", k, pair[2]))
}
img <- info[ok]

# %% Duplicates: perceptual-hash groups and identical files
DUP <- 6
groups <- cs_img_dup_groups(hashes, DUP)
md5s <- vapply(img, function(r) r$md5, "")
exact <- duplicated(md5s)
first_in_group <- vapply(seq_along(groups), function(j) groups[j] > 0 && match(groups[j], groups) == j, TRUE)

# %% Map: PCA of the classic features
F <- do.call(rbind, feats)
for (c in seq_len(ncol(F))) F[is.na(F[, c]), c] <- mean(F[, c], na.rm = TRUE)
EMBED_LABEL <- "Classic features"
mp <- if (nrow(F) >= 2) cs_img_classic_map(F) else list(Y = matrix(0, nrow(F), 2), shares = c(NaN, NaN))
Y <- mp$Y

# %% Flags
DARK <- 0.15; BRIGHT <- 0.85; BLUR <- 100
flags <- vapply(seq_along(img), function(j) {
  r <- img[[j]]
  if (exact[j] || (groups[j] > 0 && !first_in_group[j])) "Duplicate"
  else if (r$brightness < DARK) "Dark"
  else if (r$brightness > BRIGHT) "Bright"
  else if (!is.nan(r$sharpness) && r$sharpness < BLUR) "Blurry" # after exposure: very dark or bright frames have little detail anyway
  else "OK"
}, "")
for (j in seq_along(img)) img[[j]] <- c(img[[j]], list(dup_group = groups[j], exact_duplicate = exact[j], flag = flags[j], map_x = Y[j, 1], map_y = Y[j, 2]))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/describe.images/folder_defaults/out-r")
get <- function(field, type) {
  v <- lapply(img, function(r) if (is.null(r[[field]])) NA else r[[field]])
  switch(type, chr = vapply(v, function(x) if (is.na(x)) NA_character_ else as.character(x), ""),
         num = vapply(v, function(x) as.numeric(x), 0), int = vapply(v, function(x) as.integer(x), 0L),
         lgl = vapply(v, function(x) as.logical(x), TRUE))
}
art <- data.frame(row = get("row", "int"), path = get("path", "chr"), file = get("file", "chr"), format = get("format", "chr"),
                  bytes = get("bytes", "num"), md5 = get("md5", "chr"), width = get("width", "int"), height = get("height", "int"),
                  alpha = get("alpha", "lgl"), stringsAsFactors = FALSE)
for (f in c("brightness", "contrast", "mean_r", "mean_g", "mean_b", "colourfulness", "saturation", "sharpness", "entropy", "clipped_dark", "clipped_bright")) art[[f]] <- get(f, "num")
art$phash <- get("phash", "chr"); art$dup_group <- get("dup_group", "int"); art$exact_duplicate <- get("exact_duplicate", "lgl"); art$flag <- get("flag", "chr")
art$make <- get("make", "chr"); art$model <- get("model", "chr"); art$datetime <- get("datetime", "chr")
art$orientation <- get("orientation", "int"); art$exposure <- get("exposure", "num"); art$fnumber <- get("fnumber", "num")
art$iso <- get("iso", "int"); art$focal <- get("focal", "num"); art$gps <- get("gps", "lgl"); art$map_x <- get("map_x", "num"); art$map_y <- get("map_y", "num")
nanoparquet::write_parquet(art, file.path(out, "images.parquet"))

# %% Result
W <- as.numeric(art$width); H <- as.numeric(art$height); B <- art$brightness; S <- art$sharpness
values <- list(
  n_rows = nrow(df), n_images = length(img), n_no_path = sum(status == "no path"), n_missing = sum(status == "missing"),
  n_unsupported = sum(status == "unsupported"), n_unreadable = sum(status == "unreadable"),
  n_png = sum(art$format == "PNG"), n_jpeg = sum(art$format == "JPEG"), n_alpha = sum(art$alpha), bytes_total = sum(art$bytes),
  width_min = min(W), width_median = stats::median(W), width_max = max(W),
  height_min = min(H), height_median = stats::median(H), height_max = max(H),
  megapixels_median = stats::median(W * H) / 1e6, aspect_median = stats::median(W / H),
  share_portrait = mean(H > W), n_sizes = nrow(unique(data.frame(W, H))),
  brightness_mean = mean(B), brightness_sd = if (length(B) > 1) stats::sd(B) else NULL,
  contrast_mean = mean(art$contrast), colourfulness_mean = mean(art$colourfulness), saturation_mean = mean(art$saturation),
  sharpness_median = if (any(is.finite(S))) stats::median(S[is.finite(S)]) else NULL,
  entropy_mean = mean(art$entropy),
  n_dark = sum(flags == "Dark"), n_bright = sum(flags == "Bright"), n_blurry = sum(flags == "Blurry"),
  n_exif = sum(vapply(img, function(r) nz(r$make) || nz(r$model) || nz(r$datetime), TRUE)),
  n_gps = sum(vapply(img, function(r) isTRUE(r$gps), TRUE)),
  n_dup_groups = if (length(groups)) max(groups) else 0L, n_in_dup_groups = sum(groups > 0), n_exact_dups = sum(exact),
  map_share_1 = mp$shares[1], map_share_2 = mp$shares[2], embedding = EMBED_LABEL
)
n_tiff <- sum(art$format == "TIFF", na.rm = TRUE)
if (n_tiff > 0) values$n_tiff <- n_tiff  # only when TIFF files were read, so results without them keep their keys
cam_names <- vapply(img, function(r) {
  parts <- c(if (nz(r$make)) r$make, if (nz(r$model)) r$model)
  if (length(parts)) paste(parts, collapse = " ") else NA_character_
}, "")
cams <- table(cam_names[!is.na(cam_names)])
if (length(cams)) cams <- cams[order(names(cams), method = "radix")]  # no camera data: an empty table has no names
for (key in names(cams)) values[[sprintf("camera[%s]", key)]] <- as.integer(cams[[key]])
assumptions <- list(
  list(key = "formats", label = "PNG, JPEG and TIFF", status = if (values$n_unsupported) "warn" else "pass",
       detail = if (values$n_unsupported) sprintf("%d listed files are not PNG, JPEG or a readable kind of TIFF.", values$n_unsupported) else "Every readable file is PNG, JPEG or TIFF."),
  list(key = "blur_scale", label = "Sharpness depends on size and content", status = "info",
       detail = sprintf("Sharpness is measured at most %d pixels on the long side; plain images score low without being blurred.", MAX_SIDE)),
  list(key = "personal_data", label = "Personal data in metadata", status = if (values$n_gps) "warn" else "pass",
       detail = if (values$n_gps) sprintf("%d images carry GPS location data (coordinates are not read).", values$n_gps) else "No image carries GPS data.")
)
flagged <- utils::head(which(flags != "OK"), 50)
tables <- list(list(
  key = "flagged", title = "Flagged images",
  columns = list(list(key = "file", label = "File"), list(key = "flag", label = "Flag"), list(key = "brightness", label = "Brightness", type = "number"),
                 list(key = "sharpness", label = "Sharpness", type = "number"), list(key = "dup_group", label = "Duplicate group", type = "integer")),
  rows = lapply(flagged, function(j) list(file = art$file[j], flag = flags[j], brightness = art$brightness[j], sharpness = art$sharpness[j], dup_group = art$dup_group[j]))
))
if (length(cams)) tables[[2]] <- list(key = "cameras", title = "Cameras (EXIF)",
  columns = list(list(key = "camera", label = "Make and model"), list(key = "images", label = "Images", type = "integer")),
  rows = lapply(names(cams), function(k) list(camera = k, images = as.integer(cams[[k]]))))
FLAG_LEVELS <- c("OK", "Dark", "Bright", "Blurry", "Duplicate")
if (!is.null(LABEL)) {
  lab <- df[[LABEL]][art$row + 1L]
  groups_col <- ifelse(is.na(lab), "(missing)", as.character(lab)); group_title <- LABEL
} else {
  groups_col <- flags; group_title <- "Flag"
}
charts <- list(
  cs_chart("quality", "image-quality", "Brightness and sharpness", list(
    brightness = cs_col("Brightness (0–1)", B, "numeric"),
    sharpness = cs_col("Sharpness (variance of the Laplacian)", ifelse(is.nan(S), 0, S), "numeric"),
    flag = cs_col("Flag", flags, "categorical", FLAG_LEVELS),
    label = cs_col("File", art$file, "categorical")
  ), controls = list(dark = DARK, bright = BRIGHT, blur = BLUR)),
  cs_chart("sizes", "image-sizes", "Pixel sizes", list(
    width = cs_col("Width (px)", W, "numeric"), height = cs_col("Height (px)", H, "numeric"),
    group = cs_col("Format", art$format, "categorical"), label = cs_col("File", art$file, "categorical")
  )),
  cs_chart("map", "cluster-scatter", sprintf("Images by similarity (%s)", tolower(EMBED_LABEL)), list(
    x = cs_col("PC 1", Y[, 1], "numeric"), y = cs_col("PC 2", Y[, 2], "numeric"),
    cluster = cs_col(group_title, groups_col, "categorical"), label = cs_col("File", art$file, "categorical")
  ))
)
cs_publish(list(
  title = "Image collection profile (size, color, sharpness, duplicates)",
  engine = cs_engine_info("png", "jpeg", "codesplashr", "nanoparquet"),
  n = length(img),
  summary = sprintf("%d images: median %d × %d px; %d dark, %d bright, %d blurry, %d in near-duplicate groups.",
                    length(img), as.integer(values$width_median), as.integer(values$height_median), values$n_dark, values$n_bright, values$n_blurry, values$n_in_dup_groups),
  statistics = list(
    list(key = "n_images", label = "Images read", value = length(img)),
    list(key = "brightness_mean", label = "Mean brightness", value = values$brightness_mean),
    list(key = "sharpness_median", label = "Median sharpness", value = values$sharpness_median),
    list(key = "n_in_dup_groups", label = "In duplicate groups", value = values$n_in_dup_groups)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "images", path = file.path(out, "images.parquet"), format = "parquet"))
))
Python

22 images: median 62 × 48 px; 1 dark, 1 bright, 2 blurry, 3 in near-duplicate groups.

Images read
22
Mean brightness
0.5090
Median sharpness
697.19
In duplicate groups
3

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • PNG, JPEG and TIFF — 1 listed files are not PNG, JPEG or a readable kind of TIFF.
  • Sharpness depends on size and content — Sharpness is measured at most 512 pixels on the long side; plain images score low without being blurred.
  • Personal data in metadata — 1 images carry GPS location data (coordinates are not read).

Flagged images

FileFlagBrightnessSharpnessDuplicate group
gradient_a_copy.pngDuplicate0.5459111.351
gradient_a_near.pngDuplicate0.5458138.601
palette.pngBlurry0.288573.6800
dark.pngDark0.046973.1710
bright.pngBright0.960473.8870
flat_mid.pngBlurry0.502000

Cameras (EXIF)

Make and modelImages
Fixturecam FX-1001
Fixturecam FX-2001
Othercam O-11
  • 1 rows have no path and are left out.
  • 1 rows point to files that do not exist and are left out.
  • 1 rows are not PNG, JPEG or a readable kind of TIFF and are left out.
  • 1 rows could not be decoded and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image collection profile (size, color, sharpness, duplicates)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.images 1.1.0 · spec bcdfced43aa2ed60
# Dataset: ml_images (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.images import features as fx
from codesplash.images import tiff as fxt

# %% Images listed in the path column
PATH = "path"
LABEL = None
FOLDER = os.path.expanduser("")
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/ml_images.parquet"))
df = pd.read_parquet("tests/parity/fixtures/ml_images.parquet", columns=[PATH] if LABEL is None else [PATH, LABEL])
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"original\",\"formats\":[\"tiff\"],\"mode\":\"rgb\",\"normalize\":\"none\",\"orientation\":\"stored\",\"size\":[224,224]}}"), "target/academy-parity/run-8142/describe.images/folder_defaults/out-python", df, "tests/parity/fixtures/ml_images.parquet")
media_ids = cs_media.ids_of(media, df)
MAX_SIDE = 512
warnings = []
status, info, feats, hashes, thumbs, rgbs = [], [], [], [], [], []
for i, p in enumerate(df[PATH].tolist()):
    path = fx.resolve(p, FOLDER, DATA_DIR)
    if path is None:
        status.append("no path")
        info.append({"row": i, "path": None})
        continue
    r = fx.read(path)
    if r["status"] == "unsupported" and fxt.is_tiff(path):
        r = fxt.read(path, r, media, media_ids[i] if media_ids else None)  # TIFF: decoded by the host
    status.append(r["status"])
    rec = {"row": i, "path": path, "file": os.path.basename(path), "format": r.get("format"), "bytes": r.get("bytes"), "md5": r.get("md5")}
    if r["status"] == "ok":
        small = fx.fit(r["rgb"], MAX_SIDE)
        m = fx.measures(small)
        h = fx.phash(fx.luma(small))
        rec.update(width=r["width"], height=r["height"], alpha=r["alpha"], phash=fx.hex_bits(h), **m,
                   **(fxt.exif(path) if r["format"] == "TIFF" else fx.exif(path)))
        feats.append([m["brightness"], m["contrast"], m["mean_r"], m["mean_g"], m["mean_b"], m["colourfulness"], m["saturation"],
                      np.log1p(m["sharpness"]) if m["sharpness"] == m["sharpness"] else np.nan, m["entropy"], *fx.thumb(small)])
        hashes.append(h)
        rgbs.append(r["rgb"] if False else None)
    info.append(rec)
ok = [k for k, s in enumerate(status) if s == "ok"]
if not ok:
    if not status:
        cs.cs_error("CS_E_NO_ROWS")
    if all(s == "no path" for s in status):
        cs.cs_error("CS_E_ALL_MISSING", column=PATH)
    # None of the listed files could be read (missing, not PNG, JPEG or TIFF, or not decodable).
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="a PNG, JPEG or TIFF file that exists",
                count=sum(1 for s in status if s != "no path"))
for s, what in (("no path", "have no path"), ("missing", "point to files that do not exist"), ("unsupported", "are not PNG, JPEG or a readable kind of TIFF"), ("unreadable", "could not be decoded")):
    k = status.count(s)
    if k:
        warnings.append(f"{k} rows {what} and are left out.")
img = [info[k] for k in ok]

# %% Duplicates: perceptual-hash groups and identical files
DUP = 6
groups = fx.dup_groups(hashes, DUP)
seen_md5, exact = set(), []
for rec in img:
    exact.append(rec["md5"] in seen_md5)
    seen_md5.add(rec["md5"])
first_in_group = {}
for j, g in enumerate(groups):
    if g and g not in first_in_group:
        first_in_group[g] = j

# %% Map: PCA of the classic features
F = np.array(feats, dtype=float)
col_mean = np.nanmean(F, axis=0)
F = np.where(np.isnan(F), col_mean, F)
EMBED_LABEL = "Classic features"
Y, map_shares = fx.classic_map(F) if len(F) >= 2 else (np.zeros((len(F), 2)), [float("nan"), float("nan")])

# %% Flags
DARK, BRIGHT, BLUR = 0.15, 0.85, 100
flags = []
for j, rec in enumerate(img):
    if exact[j] or (groups[j] and first_in_group[groups[j]] != j):
        f = "Duplicate"
    elif rec["brightness"] < DARK:
        f = "Dark"
    elif rec["brightness"] > BRIGHT:
        f = "Bright"
    elif rec["sharpness"] == rec["sharpness"] and rec["sharpness"] < BLUR:
        f = "Blurry"  # after exposure: very dark or bright frames have little detail anyway
    else:
        f = "OK"
    flags.append(f)
    rec.update(dup_group=int(groups[j]), exact_duplicate=bool(exact[j]), flag=f, map_x=float(Y[j, 0]), map_y=float(Y[j, 1]))

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/describe.images/folder_defaults/out-python")
cols = ["row", "path", "file", "format", "bytes", "md5", "width", "height", "alpha", "brightness", "contrast", "mean_r", "mean_g", "mean_b",
        "colourfulness", "saturation", "sharpness", "entropy", "clipped_dark", "clipped_bright", "phash", "dup_group", "exact_duplicate", "flag",
        "make", "model", "datetime", "orientation", "exposure", "fnumber", "iso", "focal", "gps", "map_x", "map_y"]
art = pd.DataFrame([{c: rec.get(c) for c in cols} for rec in img], columns=cols)
for c in ("make", "model", "datetime", "phash", "flag", "format", "file", "path", "md5"):
    art[c] = art[c].astype("string")
for c in ("orientation", "iso"):
    art[c] = pd.array([None if pd.isna(v) else int(v) for v in art[c]], dtype="Int64")
for c in ("exposure", "fnumber", "focal"):
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
art["gps"] = art["gps"].astype("boolean")
art.to_parquet(os.path.join(out, "images.parquet"), index=False)

# %% Result
W = np.array([r["width"] for r in img], dtype=float)
H = np.array([r["height"] for r in img], dtype=float)
B = np.array([r["brightness"] for r in img])
S = np.array([r["sharpness"] for r in img])
values = {
    "n_rows": len(df), "n_images": len(img), "n_no_path": status.count("no path"), "n_missing": status.count("missing"),
    "n_unsupported": status.count("unsupported"), "n_unreadable": status.count("unreadable"),
    "n_png": sum(r["format"] == "PNG" for r in img), "n_jpeg": sum(r["format"] == "JPEG" for r in img),
    "n_alpha": sum(bool(r["alpha"]) for r in img), "bytes_total": int(sum(r["bytes"] for r in img)),
    "width_min": float(W.min()), "width_median": float(np.median(W)), "width_max": float(W.max()),
    "height_min": float(H.min()), "height_median": float(np.median(H)), "height_max": float(H.max()),
    "megapixels_median": float(np.median(W * H) / 1e6), "aspect_median": float(np.median(W / H)),
    "share_portrait": float(np.mean(H > W)), "n_sizes": len({(int(w), int(h)) for w, h in zip(W, H)}),
    "brightness_mean": float(B.mean()), "brightness_sd": float(B.std(ddof=1)) if len(B) > 1 else None,
    "contrast_mean": float(np.mean([r["contrast"] for r in img])),
    "colourfulness_mean": float(np.mean([r["colourfulness"] for r in img])),
    "saturation_mean": float(np.mean([r["saturation"] for r in img])),
    "sharpness_median": float(np.nanmedian(S)) if np.isfinite(S).any() else None,
    "entropy_mean": float(np.mean([r["entropy"] for r in img])),
    "n_dark": flags.count("Dark"), "n_bright": flags.count("Bright"), "n_blurry": flags.count("Blurry"),
    "n_exif": sum(1 for r in img if r.get("make") or r.get("model") or r.get("datetime")),
    "n_gps": sum(1 for r in img if r.get("gps")),
    "n_dup_groups": int(groups.max()) if len(groups) else 0, "n_in_dup_groups": int(np.sum(groups > 0)),
    "n_exact_dups": int(sum(exact)),
    "map_share_1": map_shares[0], "map_share_2": map_shares[1], "embedding": EMBED_LABEL,
}
n_tiff = sum(r["format"] == "TIFF" for r in img)
if n_tiff:
    values["n_tiff"] = n_tiff  # only when TIFF files were read, so results without them keep their keys
cams: dict[str, int] = {}
for r in img:
    if r.get("make") or r.get("model"):
        key = " ".join(x for x in (r.get("make"), r.get("model")) if x)
        cams[key] = cams.get(key, 0) + 1
for key, k in sorted(cams.items()):
    values[f"camera[{key}]"] = k
assumptions = [
    {"key": "formats", "label": "PNG, JPEG and TIFF", "status": "warn" if values["n_unsupported"] else "pass",
     "detail": f"{values['n_unsupported']} listed files are not PNG, JPEG or a readable kind of TIFF." if values["n_unsupported"] else "Every readable file is PNG, JPEG or TIFF."},
    {"key": "blur_scale", "label": "Sharpness depends on size and content", "status": "info",
     "detail": f"Sharpness is measured at most {MAX_SIDE} pixels on the long side; plain images score low without being blurred."},
    {"key": "personal_data", "label": "Personal data in metadata", "status": "warn" if values["n_gps"] else "pass",
     "detail": f"{values['n_gps']} images carry GPS location data (coordinates are not read)." if values["n_gps"] else "No image carries GPS data."},
]
flagged = [r for r in img if r["flag"] != "OK"][:50]
tables = [{
    "key": "flagged", "title": "Flagged images",
    "columns": [{"key": "file", "label": "File"}, {"key": "flag", "label": "Flag"}, {"key": "brightness", "label": "Brightness", "type": "number"},
                {"key": "sharpness", "label": "Sharpness", "type": "number"}, {"key": "dup_group", "label": "Duplicate group", "type": "integer"}],
    "rows": [{k: r.get(k) for k in ("file", "flag", "brightness", "sharpness", "dup_group")} for r in flagged],
}]
if cams:
    tables.append({"key": "cameras", "title": "Cameras (EXIF)", "columns": [{"key": "camera", "label": "Make and model"}, {"key": "images", "label": "Images", "type": "integer"}],
                   "rows": [{"camera": key, "images": k} for key, k in sorted(cams.items())]})
FLAG_LEVELS = ["OK", "Dark", "Bright", "Blurry", "Duplicate"]
if LABEL is not None:
    lab = df[LABEL].iloc[[r["row"] for r in img]]
    groups_col = ["(missing)" if pd.isna(v) else str(v) for v in lab]
    group_title = LABEL
else:
    groups_col, group_title = flags, "Flag"
charts = [
    cs.chart("quality", "image-quality", "Brightness and sharpness", {
        "brightness": cs.col("Brightness (0–1)", B, "numeric"),
        "sharpness": cs.col("Sharpness (variance of the Laplacian)", np.nan_to_num(S, nan=0.0), "numeric"),
        "flag": cs.col("Flag", flags, "categorical", FLAG_LEVELS),
        "label": cs.col("File", [r["file"] for r in img], "categorical"),
    }, controls={"dark": DARK, "bright": BRIGHT, "blur": BLUR}),
    cs.chart("sizes", "image-sizes", "Pixel sizes", {
        "width": cs.col("Width (px)", W, "numeric"),
        "height": cs.col("Height (px)", H, "numeric"),
        "group": cs.col("Format", [r["format"] for r in img], "categorical"),
        "label": cs.col("File", [r["file"] for r in img], "categorical"),
    }),
    cs.chart("map", "cluster-scatter", f"Images by similarity ({EMBED_LABEL.lower()})", {
        "x": cs.col("PC 1", Y[:, 0], "numeric"),
        "y": cs.col("PC 2", Y[:, 1], "numeric"),
        "cluster": cs.col(group_title, groups_col, "categorical"),
        "label": cs.col("File", [r["file"] for r in img], "categorical"),
    }),
]
cs.publish({
    "title": "Image collection profile (size, color, sharpness, duplicates)",
    "engine": cs.engine_info("pillow", "numpy", "pandas"),
    "n": len(img),
    "summary": f"{len(img)} images: median {int(values['width_median'])} × {int(values['height_median'])} px; {values['n_dark']} dark, {values['n_bright']} bright, {values['n_blurry']} blurry, {values['n_in_dup_groups']} in near-duplicate groups.",
    "statistics": [
        {"key": "n_images", "label": "Images read", "value": len(img)},
        {"key": "brightness_mean", "label": "Mean brightness", "value": values["brightness_mean"]},
        {"key": "sharpness_median", "label": "Median sharpness", "value": values["sharpness_median"]},
        {"key": "n_in_dup_groups", "label": "In duplicate groups", "value": values["n_in_dup_groups"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "images", "path": os.path.join(out, "images.parquet"), "format": "parquet"}],
})

This small folder has 22 readable images in 15 different pixel sizes, 1 unreadable file and 3 images in duplicate groups. Every one of those facts changes the next step: sizes decide resizing, duplicates decide the split.

03

Resizing changes the picture

Predict

Predict first

A 640 × 480 photo of a round plate is stretched to 224 × 224. What happens to the plate?

It stays a circleIt becomes an ellipseIt is cut off
Reveal

It becomes an ellipse. Stretching squeezes the width more than the height. A center crop keeps shapes but can cut off objects at the edges; letterboxing pads the short side and keeps everything, at the cost of wasted pixels.

04

Three ways to get a square

Read

Most pretrained networks take a fixed square. The image transformImage transformHow an image becomes a fixed grid: orientation, resize (stretch, crop or letterbox), gray or color, and scaling of values. decides how you get there:

  • Stretch: everything stays, shapes distort.
  • Center crop: shapes stay, borders go. A defect near the edge can vanish.
  • Letterbox: shapes and borders stay, padding fills the rest.

Fine detail is lost at any small size: a 4000-pixel scan shrunk to 224 keeps none of its small print. Pick the transform the model was pretrained with, then check a few resized images by eye.

05

Splits come before crops

Read

Photos from one camera, burst or patient look alike. Random crops, frames and flipped copies of one photo look even more alike. If those copies land on both sides of a split, the test score measures memory, not skill.

So split by sourceSplit by source (images)Keeping every image from one camera, scene, subject or burst in the same fold, so near-copies can't leak into the test set. first, then crop and augmentData augmentationTraining on randomly changed copies of each image (flipped, shifted, recolored) so the model ignores those changes. inside each training fold. CodeSplash's image quality audit flags near-duplicates that cross splits:

Image quality and duplicate auditRecorded · Python and R agreeRecorded 2026-11-25 · 39 values compared
R

74 images: 1 dark, 0 bright, 70 blurry; 1 identical copies, 2 near-duplicate pairs.

Images read
74
Mean brightness
0.3786
Median sharpness
1.513
Identical copies
1
Near-duplicate pairs
2

Plots

Brightness and sharpnessWhich images are too dark, washed out, blurry or duplicated?
View data
Brightness (0–1)FlagFileSharpness (variance of the Laplacian)
0.3951Blurrygood_00.png1.052
0.3771Blurrygood_01.png1.499
0.3765Blurrygood_02.png1.568
0.3952Blurrygood_03.png1.093
0.3771Blurrygood_04.png1.489
0.3765Blurrygood_05.png1.537
0.3952Blurrygood_06.png1.049
0.3768Blurrygood_07.png1.490
0.3764Blurrygood_08.png1.537
0.3954Blurrygood_09.png1.079
0.3772Blurrygood_10.png1.481
0.3766Blurrygood_11.png1.505
0.3954Blurrygood_12.png1.076
0.3770Blurrygood_13.png1.519
0.3767Blurrygood_14.png1.517
0.3957Blurrygood_15.png1.057
0.3775Blurrygood_16.png1.571
0.3766Blurrygood_17.png1.542
0.3953Blurrygood_18.png1.049
0.3774Blurrygood_19.png1.570
0.3766Blurrygood_20.png1.498
0.3953Blurrygood_21.png1.073
0.3763Blurrygood_22.png1.516
0.3769Blurrygood_23.png1.576
0.3952Blurrygood_24.png1.089
0.3772Blurrygood_25.png1.495
0.3763Blurrygood_26.png1.522
0.3951Blurrygood_27.png1.077
0.3770Blurrygood_28.png1.554
0.3766Blurrygood_29.png1.565
0.3959Blurrygood_30.png1.051
0.3769Blurrygood_31.png1.529
0.3765Blurrygood_32.png1.515
0.3955Blurrygood_33.png1.074
0.3770Blurrygood_34.png1.513
0.3765Blurrygood_35.png1.528
0.3952Blurrygood_36.png1.059
0.3766Blurrygood_37.png1.535
0.3766Blurrygood_38.png1.516
0.3955Blurrygood_39.png1.063
0.3771Blurrygood_40.png1.522
0.3765Blurrygood_41.png1.556
0.3955Blurrygood_42.png1.049
0.3768Blurrygood_43.png1.521
0.3763Blurrygood_44.png1.512
0.3952Blurrygood_45.png1.042
0.3770Blurrygood_46.png1.518
0.3762Blurrygood_47.png1.555
0.3958Blurrygood_48.png1.041
0.3772Blurrygood_49.png1.506
0.3765Blurrygood_50.png1.530
0.3955Blurrygood_51.png1.085
0.3768Blurrygood_52.png1.535
0.3765Blurrygood_53.png1.513
0.3957Blurrygood_54.png1.063
0.3769Blurrygood_55.png1.522
0.3767Blurrygood_56.png1.544
0.3954Blurrygood_57.png1.062
0.3766Blurrygood_58.png1.517
0.3765Duplicategood_59.png1.546

First 60 of 74 rows.

Pixel sizesAre the images a consistent size and shape, or a mix of resolutions and orientations?
View data
Height (px)FileWidth (px)
32good_00.png32
32good_01.png40
40good_02.png32
32good_03.png32
32good_04.png40
40good_05.png32
32good_06.png32
32good_07.png40
40good_08.png32
32good_09.png32
32good_10.png40
40good_11.png32
32good_12.png32
32good_13.png40
40good_14.png32
32good_15.png32
32good_16.png40
40good_17.png32
32good_18.png32
32good_19.png40
40good_20.png32
32good_21.png32
32good_22.png40
40good_23.png32
32good_24.png32
32good_25.png40
40good_26.png32
32good_27.png32
32good_28.png40
40good_29.png32
32good_30.png32
32good_31.png40
40good_32.png32
32good_33.png32
32good_34.png40
40good_35.png32
32good_36.png32
32good_37.png40
40good_38.png32
32good_39.png32
32good_40.png40
40good_41.png32
32good_42.png32
32good_43.png40
40good_44.png32
32good_45.png32
32good_46.png40
40good_47.png32
32good_48.png32
32good_49.png40
40good_50.png32
32good_51.png32
32good_52.png40
40good_53.png32
32good_54.png32
32good_55.png40
40good_56.png32
32good_57.png32
32good_58.png40
40good_59.png32

First 60 of 74 rows.

Aspect ratios (width ÷ height)How is one numeric variable distributed?
View data
Aspect ratio
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000
1
1.250
0.8000

First 60 of 74 rows.

Assumptions

  • Measured on a 256 × 256 copy — Every image was resized to 256 × 256 (stretched) before measuring.
  • Sharpness depends on content — Plain images score low without being blurred.
  • Similar scenes are not copies — 2 near-duplicate pairs: look at them before removing any.

Flagged images

RowFileFlagBrightnessSharpness
1good_00.pngBlurry0.39511.052
2good_01.pngBlurry0.37711.499
3good_02.pngBlurry0.37651.568
4good_03.pngBlurry0.39521.093
5good_04.pngBlurry0.37711.489
6good_05.pngBlurry0.37651.537
7good_06.pngBlurry0.39521.049
8good_07.pngBlurry0.37681.490
9good_08.pngBlurry0.37641.537
10good_09.pngBlurry0.39541.079
11good_10.pngBlurry0.37721.481
12good_11.pngBlurry0.37661.505
13good_12.pngBlurry0.39541.076
14good_13.pngBlurry0.37701.519
15good_14.pngBlurry0.37671.517
16good_15.pngBlurry0.39571.057
17good_16.pngBlurry0.37751.571
18good_17.pngBlurry0.37661.542
19good_18.pngBlurry0.39531.049
20good_19.pngBlurry0.37741.570
21good_20.pngBlurry0.37661.498
22good_21.pngBlurry0.39531.073
23good_22.pngBlurry0.37631.516
24good_23.pngBlurry0.37691.576
25good_24.pngBlurry0.39521.089
26good_25.pngBlurry0.37721.495
27good_26.pngBlurry0.37631.522
28good_27.pngBlurry0.39511.077
29good_28.pngBlurry0.37701.554
30good_29.pngBlurry0.37661.565
31good_30.pngBlurry0.39591.051
32good_31.pngBlurry0.37691.529
33good_32.pngBlurry0.37651.515
34good_33.pngBlurry0.39551.074
35good_34.pngBlurry0.37701.513
36good_35.pngBlurry0.37651.528
37good_36.pngBlurry0.39521.059
38good_37.pngBlurry0.37661.535
39good_38.pngBlurry0.37661.516
40good_39.pngBlurry0.39551.063

First 40 of 50 rows.

Copies and near-duplicates

KindRowFileRowCopyBits apartSplitCopy's split
identical4good_03.png73good_03_copy.png0traintest
near6good_05.png74good_05_edit.png0traintest
near30good_29.png60good_59.png6traintest

Sources on both sides of the split

SourceTraining imagesHeld-out images
cam2195

Quality by label

labelImagesMean brightnessMean contrastMedian sharpnessFlagged
defect40.37210.14162.0004
good700.37890.14651.51370
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Image quality and duplicate audit
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.image_quality 1.0.0 · spec ae37c18b80f5568e
# Dataset: img2_parts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Images listed in the path column (one decoded 256 x 256 copy per file)
PATH <- "path"
LABEL <- "label"
SPLIT <- "split"
SOURCE <- "source"
WIDTH <- "width"
HEIGHT <- "height"
cols_ <- unique(c(PATH, LABEL, SPLIT, SOURCE, WIDTH, HEIGHT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img2_parts.parquet", col_select = cols_))
if (!nrow(df)) cs_error("CS_E_NO_ROWS")
warnings <- character(0)
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"stretch\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[256,256]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/describe.image_quality/parts_split_source_sizes/out-r", df,
                        "tests/parity/fixtures/img2_parts.parquet")
media_ids <- cs_media_ids(media, df)

text_ <- function(v) { v <- as.character(v); v[!is.na(v) & !nzchar(v)] <- NA_character_; v }
paths_ <- text_(df[[PATH]])
rd_ <- cs_imgc_read(media, media_ids, paths_)
ok <- rd_$ok; n_no_path <- rd_$n_no_path; n_unreadable <- rd_$n_unreadable; X <- rd_$X  # X: (n, c, h, w) on 0-1
if (!length(ok)) {
  if (n_no_path == nrow(df)) cs_error("CS_E_ALL_MISSING", column = PATH)
  # None of the listed files could be decoded.
  cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an image file that can be decoded", count = n_unreadable)
}
if (n_no_path) warnings <- c(warnings, sprintf("%d rows have no path and are left out.", n_no_path))
if (n_unreadable) warnings <- c(warnings, sprintf("%d files could not be decoded and are left out.", n_unreadable))
n <- length(ok)

# %% Measures and hashes
HASH <- "phash"
DUP <- 6
meas <- vector("list", n)
bits <- list(ahash = matrix(FALSE, n, 64), dhash = matrix(FALSE, n, 64), phash = matrix(FALSE, n, 64))
for (i in seq_len(n)) {
  t_ <- array(X[i, , , ], dim(X)[-1])
  meas[[i]] <- cs_img_measures(aperm(t_, c(2, 3, 1)) * 255)
  hs <- cs_imgh_image(t_)
  for (k in names(bits)) bits[[k]][i, ] <- hs[[k]]
}
ids <- media_ids[ok]
files <- basename(paths_[ok])
rows1 <- ok
m_ <- function(key) vapply(meas, function(m) m[[key]], 0)

# %% Copies: identical files (same content hash) and near-duplicates (hash distance)
exact <- cs_imgh_exact_pairs(ids)
exact_group <- cs_imgh_exact_groups(ids)
near_all <- cs_imgh_near_pairs(bits[[HASH]], DUP)
near <- near_all[ids[near_all[, 1]] != ids[near_all[, 2]], , drop = FALSE]
near_group <- cs_imgh_groups(n, near)
sides <- if (!is.null(SPLIT)) cs_imgh_split_side(text_(df[[SPLIT]])[ok]) else rep(NA_integer_, n)
cross_exact <- cs_imgh_cross_split(exact, sides)
cross_near <- cs_imgh_cross_split(near, sides)
held_ <- function(p) length(unique(ifelse(sides[p[, 1]] == 0L, p[, 1], p[, 2])))
sources <- if (!is.null(SOURCE)) text_(df[[SOURCE]])[ok] else rep(NA_character_, n)
across <- if (!is.null(SOURCE) && !is.null(SPLIT)) cs_imgh_groups_across(sources, sides) else character(0)

# %% Flags
DARK <- 0.15; BRIGHT <- 0.85; BLUR <- 100
first_near <- integer(0)
for (j in seq_len(n)) {
  g <- as.character(near_group[j])
  if (near_group[j] > 0 && is.na(first_near[g])) first_near[g] <- j
}
later_exact <- exact[, 2]
flags <- character(n)
for (j in seq_len(n)) {
  m <- meas[[j]]
  copy <- (exact_group[j] > 0 && j %in% later_exact) || (near_group[j] > 0 && first_near[[as.character(near_group[j])]] != j)
  flags[j] <- if (copy) "Duplicate" else if (m$brightness < DARK) "Dark" else if (m$brightness > BRIGHT) "Bright" else
    if (!is.nan(m$sharpness) && m$sharpness < BLUR) "Blurry" else "OK"
}

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/describe.image_quality/parts_split_source_sizes/out-r")
art <- data.frame(row = as.integer(rows1), media_id = ids, file = files, stringsAsFactors = FALSE)
for (k in c("brightness", "contrast", "colourfulness", "saturation", "sharpness", "entropy", "clipped_dark", "clipped_bright")) art[[if (k == "colourfulness") "colorfulness" else k]] <- m_(k)
for (k in c("ahash", "dhash", "phash")) art[[k]] <- cs_imgh_hex(bits[[k]])
art$exact_group <- as.integer(exact_group)
art$near_group <- as.integer(near_group)
art$flag <- flags
nanoparquet::write_parquet(art, file.path(out, "images.parquet"))

split_of_ <- function(i) if (is.null(SPLIT)) NA_character_ else text_(df[[SPLIT]])[ok[i]]
pair_rows_ <- function(p, kind) {
  lapply(seq_len(nrow(p)), function(r) {
    i <- p[r, 1]; j <- p[r, 2]
    list(kind = kind, row_a = rows1[i], row_b = rows1[j], file_a = files[i], file_b = files[j], distance = as.integer(p[r, 3]),
         split_a = split_of_(i), split_b = split_of_(j))
  })
}
pair_rows <- c(pair_rows_(exact, "identical"), pair_rows_(near, "near"))
pairs_df <- data.frame(
  kind = vapply(pair_rows, function(r) r$kind, ""), row_a = vapply(pair_rows, function(r) as.integer(r$row_a), 0L),
  row_b = vapply(pair_rows, function(r) as.integer(r$row_b), 0L), file_a = vapply(pair_rows, function(r) r$file_a, ""),
  file_b = vapply(pair_rows, function(r) r$file_b, ""), distance = vapply(pair_rows, function(r) r$distance, 0L),
  split_a = vapply(pair_rows, function(r) r$split_a, ""), split_b = vapply(pair_rows, function(r) r$split_b, ""),
  stringsAsFactors = FALSE
)
nanoparquet::write_parquet(pairs_df, file.path(out, "pairs.parquet"))

# %% Result
B <- m_("brightness")
S <- m_("sharpness")
if (!is.null(WIDTH) && !is.null(HEIGHT)) {
  W <- suppressWarnings(as.numeric(df[[WIDTH]][ok])); H <- suppressWarnings(as.numeric(df[[HEIGHT]][ok]))
  good <- is.finite(W) & is.finite(H) & W > 0 & H > 0
} else {
  W <- numeric(0); H <- numeric(0); good <- logical(0)
}
sized <- any(good)
nul <- function(x) if (sized) x else NULL
values <- list(
  n_rows = nrow(df), n_images = n, n_no_path = n_no_path, n_unreadable = n_unreadable,
  brightness_mean = mean(B), brightness_sd = if (n > 1) stats::sd(B) else NULL,
  contrast_mean = mean(m_("contrast")), colorfulness_mean = mean(m_("colourfulness")), saturation_mean = mean(m_("saturation")),
  sharpness_median = stats::median(S), entropy_mean = mean(m_("entropy")),
  n_dark = sum(flags == "Dark"), n_bright = sum(flags == "Bright"), n_blurry = sum(flags == "Blurry"),
  n_exact_copies = nrow(exact), n_exact_groups = if (n) max(exact_group) else 0L,
  n_near_pairs = nrow(near), n_near_groups = if (n) max(near_group) else 0L, n_in_near_groups = sum(near_group > 0),
  n_train = sum(sides == 1L, na.rm = TRUE), n_held_out = sum(sides == 0L, na.rm = TRUE),
  n_cross_exact = held_(cross_exact), n_cross_near = held_(cross_near),
  n_sources = length(unique(sources[!is.na(sources)])), n_groups_across = length(across),
  width_median = nul(stats::median(W[good])), height_median = nul(stats::median(H[good])),
  aspect_median = nul(stats::median(W[good] / H[good])), share_portrait = nul(mean(H[good] > W[good])),
  megapixels_median = nul(stats::median(W[good] * H[good]) / 1e6),
  n_sizes = nul(nrow(unique(data.frame(w = W[good], h = H[good])))),
  hash = HASH, threshold = DUP
)
group_rows <- list()
if (!is.null(LABEL)) {
  lab_ <- text_(df[[LABEL]])[ok]
  lab_[is.na(lab_)] <- "(missing)"
  for (lv in sort(unique(lab_), method = "radix")) {
    idx <- which(lab_ == lv)
    values[[sprintf("group_n[%s]", lv)]] <- length(idx)
    values[[sprintf("group_brightness[%s]", lv)]] <- mean(B[idx])
    values[[sprintf("group_sharpness[%s]", lv)]] <- stats::median(S[idx])
    group_rows[[length(group_rows) + 1L]] <- list(group = lv, n = length(idx), brightness = mean(B[idx]), contrast = mean(m_("contrast")[idx]),
                                                  sharpness = stats::median(S[idx]), flagged = sum(flags[idx] != "OK"))
  }
}
assumptions <- list(
  list(key = "analysis_copy", label = "Measured on a 256 × 256 copy", status = "info",
       detail = "Every image was resized to 256 × 256 (stretched) before measuring."),
  list(key = "blur_scale", label = "Sharpness depends on content", status = "info",
       detail = "Plain images score low without being blurred."),
  list(key = "hashes_similar_scenes", label = "Similar scenes are not copies", status = if (nrow(near)) "warn" else "pass",
       detail = if (nrow(near)) sprintf("%d near-duplicate pairs: look at them before removing any.", nrow(near)) else "No near-duplicate pairs at this distance.")
)
flagged <- utils::head(which(flags != "OK"), 50L)
pair_cols <- c(list(list(key = "kind", label = "Kind"), list(key = "row_a", label = "Row", type = "integer"), list(key = "file_a", label = "File"),
                    list(key = "row_b", label = "Row", type = "integer"), list(key = "file_b", label = "Copy"), list(key = "distance", label = "Bits apart", type = "integer")),
               if (!is.null(SPLIT)) list(list(key = "split_a", label = "Split"), list(key = "split_b", label = "Copy's split")) else list())
tables <- list(
  list(key = "flagged", title = "Flagged images",
       columns = list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File"), list(key = "flag", label = "Flag"),
                      list(key = "brightness", label = "Brightness", type = "number"), list(key = "sharpness", label = "Sharpness", type = "number")),
       rows = lapply(flagged, function(j) list(row = rows1[j], file = files[j], flag = flags[j], brightness = meas[[j]]$brightness, sharpness = meas[[j]]$sharpness))),
  list(key = "pairs", title = "Copies and near-duplicates", columns = pair_cols,
       rows = lapply(utils::head(pair_rows, 200L), function(r) if (is.null(SPLIT)) r[setdiff(names(r), c("split_a", "split_b"))] else r))
)
if (length(across)) {
  tables[[length(tables) + 1L]] <- list(key = "across", title = "Sources on both sides of the split",
    columns = list(list(key = "source", label = "Source"), list(key = "train", label = "Training images", type = "integer"), list(key = "held_out", label = "Held-out images", type = "integer")),
    rows = lapply(utils::head(across, 200L), function(g) list(source = g, train = sum(sources == g & sides == 1L, na.rm = TRUE), held_out = sum(sources == g & sides == 0L, na.rm = TRUE))))
}
if (!is.null(LABEL)) {
  tables[[length(tables) + 1L]] <- list(key = "groups", title = paste("Quality by", LABEL),
    columns = list(list(key = "group", label = LABEL), list(key = "n", label = "Images", type = "integer"), list(key = "brightness", label = "Mean brightness", type = "number"),
                   list(key = "contrast", label = "Mean contrast", type = "number"), list(key = "sharpness", label = "Median sharpness", type = "number"), list(key = "flagged", label = "Flagged", type = "integer")),
    rows = group_rows)
}
FLAG_LEVELS <- c("OK", "Dark", "Bright", "Blurry", "Duplicate")
charts <- list(cs_chart("quality", "image-quality", "Brightness and sharpness", list(
  brightness = cs_col("Brightness (0–1)", B, "numeric"),
  sharpness = cs_col("Sharpness (variance of the Laplacian)", S, "numeric"),
  flag = cs_col("Flag", flags, "categorical", FLAG_LEVELS),
  label = cs_col("File", files, "categorical")
), controls = list(dark = DARK, bright = BRIGHT, blur = BLUR)))
if (sized) {
  charts[[length(charts) + 1L]] <- cs_chart("sizes", "image-sizes", "Pixel sizes", list(
    width = cs_col("Width (px)", W[good], "numeric"),
    height = cs_col("Height (px)", H[good], "numeric"),
    label = cs_col("File", files[good], "categorical")
  ))
  charts[[length(charts) + 1L]] <- cs_chart("aspect", "histogram", "Aspect ratios (width ÷ height)", list(x = cs_col("Aspect ratio", W[good] / H[good], "numeric")))
}
cs_publish(list(
  title = "Image quality and duplicate audit",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = sprintf("%d images: %d dark, %d bright, %d blurry; %d identical copies, %d near-duplicate pairs.", n, values$n_dark, values$n_bright, values$n_blurry, nrow(exact), nrow(near)),
  statistics = list(
    list(key = "n_images", label = "Images read", value = n),
    list(key = "brightness_mean", label = "Mean brightness", value = values$brightness_mean),
    list(key = "sharpness_median", label = "Median sharpness", value = values$sharpness_median),
    list(key = "n_exact_copies", label = "Identical copies", value = nrow(exact)),
    list(key = "n_near_pairs", label = "Near-duplicate pairs", value = nrow(near))
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = as.list(warnings),
  artifacts = list(list(key = "images", path = file.path(out, "images.parquet"), format = "parquet"),
                   list(key = "pairs", path = file.path(out, "pairs.parquet"), format = "parquet"))
))
Python

74 images: 1 dark, 0 bright, 70 blurry; 1 identical copies, 2 near-duplicate pairs.

Images read
74
Mean brightness
0.3786
Median sharpness
1.513
Identical copies
1
Near-duplicate pairs
2

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Measured on a 256 × 256 copy — Every image was resized to 256 × 256 (stretched) before measuring.
  • Sharpness depends on content — Plain images score low without being blurred.
  • Similar scenes are not copies — 2 near-duplicate pairs: look at them before removing any.

Flagged images

RowFileFlagBrightnessSharpness
1good_00.pngBlurry0.39511.052
2good_01.pngBlurry0.37711.499
3good_02.pngBlurry0.37651.568
4good_03.pngBlurry0.39521.093
5good_04.pngBlurry0.37711.489
6good_05.pngBlurry0.37651.537
7good_06.pngBlurry0.39521.049
8good_07.pngBlurry0.37681.490
9good_08.pngBlurry0.37641.537
10good_09.pngBlurry0.39541.079
11good_10.pngBlurry0.37721.481
12good_11.pngBlurry0.37661.505
13good_12.pngBlurry0.39541.076
14good_13.pngBlurry0.37701.519
15good_14.pngBlurry0.37671.517
16good_15.pngBlurry0.39571.057
17good_16.pngBlurry0.37751.571
18good_17.pngBlurry0.37661.542
19good_18.pngBlurry0.39531.049
20good_19.pngBlurry0.37741.570
21good_20.pngBlurry0.37661.498
22good_21.pngBlurry0.39531.073
23good_22.pngBlurry0.37631.516
24good_23.pngBlurry0.37691.576
25good_24.pngBlurry0.39521.089
26good_25.pngBlurry0.37721.495
27good_26.pngBlurry0.37631.522
28good_27.pngBlurry0.39511.077
29good_28.pngBlurry0.37701.554
30good_29.pngBlurry0.37661.565
31good_30.pngBlurry0.39591.051
32good_31.pngBlurry0.37691.529
33good_32.pngBlurry0.37651.515
34good_33.pngBlurry0.39551.074
35good_34.pngBlurry0.37701.513
36good_35.pngBlurry0.37651.528
37good_36.pngBlurry0.39521.059
38good_37.pngBlurry0.37661.535
39good_38.pngBlurry0.37661.516
40good_39.pngBlurry0.39551.063

First 40 of 50 rows.

Copies and near-duplicates

KindRowFileRowCopyBits apartSplitCopy's split
identical4good_03.png73good_03_copy.png0traintest
near6good_05.png74good_05_edit.png0traintest
near30good_29.png60good_59.png6traintest

Sources on both sides of the split

SourceTraining imagesHeld-out images
cam2195

Quality by label

labelImagesMean brightnessMean contrastMedian sharpnessFlagged
defect40.37210.14162.0004
good700.37890.14651.51370
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image quality and duplicate audit
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.image_quality 1.0.0 · spec ae37c18b80f5568e
# Dataset: img2_parts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.images import features as fx
from codesplash.images import hashes as hx

# %% Images listed in the path column (one decoded 256 x 256 copy per file)
PATH = "path"
LABEL = "label"
SPLIT = "split"
SOURCE = "source"
WIDTH = "width"
HEIGHT = "height"
_cols = list(dict.fromkeys(c for c in (PATH, LABEL, SPLIT, SOURCE, WIDTH, HEIGHT) if c is not None))
df = pd.read_parquet("tests/parity/fixtures/img2_parts.parquet", columns=_cols)
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"stretch\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[256,256]}}"), "target/academy-parity/run-8142/describe.image_quality/parts_split_source_sizes/out-python", df, "tests/parity/fixtures/img2_parts.parquet")
media_ids = cs_media.ids_of(media, df)

def _text(v):
    return None if pd.isna(v) else str(v)  # None, NaN, pd.NA

from codesplash.images import collection as cimg

ok, n_no_path, n_unreadable, X = cimg.read(media, media_ids, df[PATH].tolist())  # X: float32 (n, c, h, w) on 0–1
if not ok:
    if n_no_path == len(df):
        cs.cs_error("CS_E_ALL_MISSING", column=PATH)
    # None of the listed files could be decoded.
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an image file that can be decoded", count=n_unreadable)
if n_no_path:
    warnings.append(f"{n_no_path} rows have no path and are left out.")
if n_unreadable:
    warnings.append(f"{n_unreadable} files could not be decoded and are left out.")

# %% Measures and hashes
HASH = "phash"
DUP = 6
meas, bits = [], {k: [] for k in hx.KINDS}
for i in range(len(ok)):
    t = X[i].astype(np.float64)
    meas.append(fx.measures(np.transpose(t, (1, 2, 0)) * 255))
    for k, b in hx.image_hashes(t).items():
        bits[k].append(b)
bits = {k: np.array(v, dtype=bool).reshape(len(ok), 64) for k, v in bits.items()}
ids = [media_ids[k] for k in ok]
files = [os.path.basename(str(df[PATH].iloc[k])) for k in ok]
rows1 = [k + 1 for k in ok]  # 1-based input rows

# %% Copies: identical files (same content hash) and near-duplicates (hash distance)
exact = hx.exact_pairs(ids)
exact_group = hx.exact_groups(ids)
near_all = hx.near_pairs(bits[HASH], DUP)
near = near_all[[ids[i] != ids[j] for i, j, _ in near_all]] if len(near_all) else near_all
near_group = hx.groups_from_pairs(len(ok), near)
sides = [hx.split_side(_text(df[SPLIT].iloc[k])) for k in ok] if SPLIT is not None else [None] * len(ok)
cross_exact = hx.cross_split(exact, sides)
cross_near = hx.cross_split(near, sides)
held = lambda pairs: sorted({int(i) if sides[i] == 0 else int(j) for i, j, _ in pairs})
sources = [_text(df[SOURCE].iloc[k]) for k in ok] if SOURCE is not None else [None] * len(ok)
across = hx.groups_across_splits(sources, sides) if SOURCE is not None and SPLIT is not None else []

# %% Flags
DARK, BRIGHT, BLUR = 0.15, 0.85, 100
first_near = {}
for j, g in enumerate(near_group):
    if g and g not in first_near:
        first_near[g] = j
later_exact = {int(p[1]) for p in exact}
flags = []
for j, m in enumerate(meas):
    copy = (exact_group[j] and j in later_exact) or (near_group[j] and first_near[near_group[j]] != j)
    if copy:
        f = "Duplicate"
    elif m["brightness"] < DARK:
        f = "Dark"
    elif m["brightness"] > BRIGHT:
        f = "Bright"
    elif m["sharpness"] == m["sharpness"] and m["sharpness"] < BLUR:
        f = "Blurry"
    else:
        f = "OK"
    flags.append(f)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/describe.image_quality/parts_split_source_sizes/out-python")
art = pd.DataFrame({
    "row": np.array(rows1, dtype=np.int64),
    "media_id": pd.array(ids, dtype="string"),
    "file": pd.array(files, dtype="string"),
    **{name: np.array([m[k] for m in meas], dtype=np.float64) for name, k in (("brightness", "brightness"), ("contrast", "contrast"), ("colorfulness", "colourfulness"), ("saturation", "saturation"), ("sharpness", "sharpness"), ("entropy", "entropy"), ("clipped_dark", "clipped_dark"), ("clipped_bright", "clipped_bright"))},
    **{k: pd.array(hx.to_hex(bits[k]), dtype="string") for k in hx.KINDS},
    "exact_group": np.asarray(exact_group, dtype=np.int64),
    "near_group": np.asarray(near_group, dtype=np.int64),
    "flag": pd.array(flags, dtype="string"),
})
art.to_parquet(os.path.join(out, "images.parquet"), index=False)


def _pair_rows(pairs, kind):
    return [{"kind": kind, "row_a": rows1[int(i)], "row_b": rows1[int(j)], "file_a": files[int(i)], "file_b": files[int(j)],
             "distance": int(d), "split_a": None if SPLIT is None else _text(df[SPLIT].iloc[ok[int(i)]]),
             "split_b": None if SPLIT is None else _text(df[SPLIT].iloc[ok[int(j)]])} for i, j, d in pairs]


pair_rows = _pair_rows(exact, "identical") + _pair_rows(near, "near")
pairs_df = pd.DataFrame(pair_rows, columns=["kind", "row_a", "row_b", "file_a", "file_b", "distance", "split_a", "split_b"])
for c in ("kind", "file_a", "file_b", "split_a", "split_b"):
    pairs_df[c] = pairs_df[c].astype("string")
for c in ("row_a", "row_b", "distance"):
    pairs_df[c] = pairs_df[c].astype(np.int64)
pairs_df.to_parquet(os.path.join(out, "pairs.parquet"), index=False)

# %% Result
B = np.array([m["brightness"] for m in meas])
S = np.array([m["sharpness"] for m in meas])
if WIDTH is not None and HEIGHT is not None:
    W = pd.to_numeric(df[WIDTH].iloc[ok], errors="coerce").to_numpy(dtype=np.float64)
    H = pd.to_numeric(df[HEIGHT].iloc[ok], errors="coerce").to_numpy(dtype=np.float64)
    good = np.isfinite(W) & np.isfinite(H) & (W > 0) & (H > 0)
else:
    W = H = np.zeros(0)
    good = np.zeros(0, dtype=bool)
sized = good.any()
values = {
    "n_rows": len(df), "n_images": len(ok), "n_no_path": n_no_path, "n_unreadable": n_unreadable,
    "brightness_mean": float(B.mean()), "brightness_sd": float(B.std(ddof=1)) if len(B) > 1 else None,
    "contrast_mean": float(np.mean([m["contrast"] for m in meas])),
    "colorfulness_mean": float(np.mean([m["colourfulness"] for m in meas])),
    "saturation_mean": float(np.mean([m["saturation"] for m in meas])),
    "sharpness_median": float(np.median(S)),
    "entropy_mean": float(np.mean([m["entropy"] for m in meas])),
    "n_dark": flags.count("Dark"), "n_bright": flags.count("Bright"), "n_blurry": flags.count("Blurry"),
    "n_exact_copies": len(exact), "n_exact_groups": int(exact_group.max()) if len(exact_group) else 0,
    "n_near_pairs": len(near), "n_near_groups": int(near_group.max()) if len(near_group) else 0,
    "n_in_near_groups": int(np.sum(near_group > 0)),
    "n_train": sum(1 for s in sides if s == 1), "n_held_out": sum(1 for s in sides if s == 0),
    "n_cross_exact": len(held(cross_exact)), "n_cross_near": len(held(cross_near)),
    "n_sources": len({s for s in sources if s is not None}), "n_groups_across": len(across),
    "width_median": float(np.median(W[good])) if sized else None, "height_median": float(np.median(H[good])) if sized else None,
    "aspect_median": float(np.median(W[good] / H[good])) if sized else None,
    "share_portrait": float(np.mean(H[good] > W[good])) if sized else None,
    "megapixels_median": float(np.median(W[good] * H[good]) / 1e6) if sized else None,
    "n_sizes": len({(float(w), float(h)) for w, h in zip(W[good], H[good])}) if sized else None,
    "hash": HASH, "threshold": DUP,
}
if LABEL is not None:
    _lab = ["(missing)" if _text(df[LABEL].iloc[k]) is None else _text(df[LABEL].iloc[k]) for k in ok]
    group_rows = []
    for lv in sorted(set(_lab)):
        idx = [j for j, v in enumerate(_lab) if v == lv]
        values[f"group_n[{lv}]"] = len(idx)
        values[f"group_brightness[{lv}]"] = float(B[idx].mean())
        values[f"group_sharpness[{lv}]"] = float(np.median(S[idx]))
        group_rows.append({"group": lv, "n": len(idx), "brightness": float(B[idx].mean()), "contrast": float(np.mean([meas[j]["contrast"] for j in idx])),
                           "sharpness": float(np.median(S[idx])), "flagged": sum(1 for j in idx if flags[j] != "OK")})
assumptions = [
    {"key": "analysis_copy", "label": "Measured on a 256 × 256 copy", "status": "info",
     "detail": "Every image was resized to 256 × 256 (stretched) before measuring."},
    {"key": "blur_scale", "label": "Sharpness depends on content", "status": "info",
     "detail": "Plain images score low without being blurred."},
    {"key": "hashes_similar_scenes", "label": "Similar scenes are not copies", "status": "warn" if len(near) else "pass",
     "detail": f"{len(near)} near-duplicate pairs: look at them before removing any." if len(near) else "No near-duplicate pairs at this distance."},
]
flagged = [j for j, f in enumerate(flags) if f != "OK"][:50]
tables = [{
    "key": "flagged", "title": "Flagged images",
    "columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File"}, {"key": "flag", "label": "Flag"},
                {"key": "brightness", "label": "Brightness", "type": "number"}, {"key": "sharpness", "label": "Sharpness", "type": "number"}],
    "rows": [{"row": rows1[j], "file": files[j], "flag": flags[j], "brightness": meas[j]["brightness"], "sharpness": meas[j]["sharpness"]} for j in flagged],
}, {
    "key": "pairs", "title": "Copies and near-duplicates",
    "columns": [{"key": "kind", "label": "Kind"}, {"key": "row_a", "label": "Row", "type": "integer"}, {"key": "file_a", "label": "File"},
                {"key": "row_b", "label": "Row", "type": "integer"}, {"key": "file_b", "label": "Copy"}, {"key": "distance", "label": "Bits apart", "type": "integer"}]
               + ([{"key": "split_a", "label": "Split"}, {"key": "split_b", "label": "Copy's split"}] if SPLIT is not None else []),
    "rows": [{k: v for k, v in r.items() if SPLIT is not None or not k.startswith("split")} for r in pair_rows[:200]],
}]
if across:
    tables.append({"key": "across", "title": "Sources on both sides of the split",
                   "columns": [{"key": "source", "label": "Source"}, {"key": "train", "label": "Training images", "type": "integer"}, {"key": "held_out", "label": "Held-out images", "type": "integer"}],
                   "rows": [{"source": g, "train": sum(1 for s, sd in zip(sources, sides) if s == g and sd == 1),
                             "held_out": sum(1 for s, sd in zip(sources, sides) if s == g and sd == 0)} for g in across[:200]]})
if LABEL is not None:
    tables.append({"key": "groups", "title": f"Quality by {LABEL}",
                   "columns": [{"key": "group", "label": LABEL}, {"key": "n", "label": "Images", "type": "integer"}, {"key": "brightness", "label": "Mean brightness", "type": "number"},
                               {"key": "contrast", "label": "Mean contrast", "type": "number"}, {"key": "sharpness", "label": "Median sharpness", "type": "number"}, {"key": "flagged", "label": "Flagged", "type": "integer"}],
                   "rows": group_rows})
FLAG_LEVELS = ["OK", "Dark", "Bright", "Blurry", "Duplicate"]
charts = [cs.chart("quality", "image-quality", "Brightness and sharpness", {
    "brightness": cs.col("Brightness (0–1)", B, "numeric"),
    "sharpness": cs.col("Sharpness (variance of the Laplacian)", S, "numeric"),
    "flag": cs.col("Flag", flags, "categorical", FLAG_LEVELS),
    "label": cs.col("File", files, "categorical"),
}, controls={"dark": DARK, "bright": BRIGHT, "blur": BLUR})]
if sized:
    charts.append(cs.chart("sizes", "image-sizes", "Pixel sizes", {
        "width": cs.col("Width (px)", W[good], "numeric"),
        "height": cs.col("Height (px)", H[good], "numeric"),
        "label": cs.col("File", [f for f, g in zip(files, good) if g], "categorical"),
    }))
    charts.append(cs.chart("aspect", "histogram", "Aspect ratios (width ÷ height)", {"x": cs.col("Aspect ratio", W[good] / H[good], "numeric")}))
cs.publish({
    "title": "Image quality and duplicate audit",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(ok),
    "summary": f"{len(ok)} images: {values['n_dark']} dark, {values['n_bright']} bright, {values['n_blurry']} blurry; {len(exact)} identical copies, {len(near)} near-duplicate pairs.",
    "statistics": [
        {"key": "n_images", "label": "Images read", "value": len(ok)},
        {"key": "brightness_mean", "label": "Mean brightness", "value": values["brightness_mean"]},
        {"key": "sharpness_median", "label": "Median sharpness", "value": values["sharpness_median"]},
        {"key": "n_exact_copies", "label": "Identical copies", "value": len(exact)},
        {"key": "n_near_pairs", "label": "Near-duplicate pairs", "value": len(near)},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "images", "path": os.path.join(out, "images.parquet"), "format": "parquet"},
                  {"key": "pairs", "path": os.path.join(out, "pairs.parquet"), "format": "parquet"}],
})
06

Watch a leak happen

Explore

The same mechanism in a table: when near-copies of test rows are in training, the test score climbs while the model learns nothing new. Turn the leak on and off.

DExplorable · Leakage detective

Why does a model that scores brilliantly in testing fail on real data?

Read the pipeline on the left. Will its cross-validation score overstate real-world accuracy by more than 6 points?

How sure?

The pipeline

200
60
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

07

What runs in CodeSplash

Read
08

Check: images as data

Checkpoint

Check yourself

A PyTorch model expects input of shape 3 × 224 × 224. You pass a 224 × 224 × 3 array without changing it. What happens?

Show the answer

Answer: a

If the sizes line up the call can succeed silently. Check the shape and the color order at every hand-off between libraries.

Check yourself

You inspect circuit boards where scratches often sit near the edge. Which resizing is safest?

Show the answer

Answer: b

A center crop can cut off the very defect you look for. Letterboxing or tiling keeps every pixel in view.

Check yourself

Each of 50 patients has 20 skin photos. Which split gives an honest test score for new patients?

Show the answer

Answer: b

Photos of one patient share skin tone, lighting and camera. Split by patient so the test set contains only people the model hasn't seen.

Check yourself

Put the steps in order.

  1. 1Group images by source and split the groups
  2. 2Train, then score once on the untouched test images
  3. 3Augment the training images only
  4. 4Resize the way the pretrained model expects

Show the answer

The order:

  1. Group images by source and split the groups
  2. Resize the way the pretrained model expects
  3. Augment the training images only
  4. Train, then score once on the untouched test images

Splitting first keeps augmented copies of one photo on one side. Test images get the same resize but no augmentation.

09

Recap

Recap
  • An image is a tensor with a shape, a range and a channel order; mismatches run silently.
  • Profile the collection first: sizes, unreadable files and duplicates shape every later step.
  • Stretching distorts, cropping cuts, letterboxing pads; small sizes lose fine detail.
  • Split by source before cropping or augmenting, or the test score measures memory.

Concepts in this lesson