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.
What runs in CodeSplash
- Image collection profile (size, color, sharpness, duplicates) Experimental
- Image quality and duplicate audit Experimental
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
A grid of numbers
ReadA 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.
What a folder really holds
ReadBefore any model, profile the collection. CodeSplash links image files in place and reads them the same way every time:
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
View data
| Brightness (0–1) | Flag | File | Sharpness (variance of the Laplacian) |
|---|---|---|---|
| 0.5459 | OK | gradient_a.png | 111.35 |
| 0.5459 | Duplicate | gradient_a_copy.png | 111.35 |
| 0.5458 | Duplicate | gradient_a_near.png | 138.60 |
| 0.3877 | OK | gradient_b.png | 111.66 |
| 0.5002 | OK | stripes_fine.png | 22408.52 |
| 0.5002 | OK | stripes_blurred.png | 427.86 |
| 0.5964 | OK | stripes_wide.png | 4403.90 |
| 0.5294 | OK | checker.png | 35891.72 |
| 0.5096 | OK | checker_gray.png | 27468.42 |
| 0.2080 | OK | checker_alpha.png | 966.52 |
| 0.2885 | Blurry | palette.png | 73.680 |
| 0.0469 | Dark | dark.png | 73.171 |
| 0.9604 | Bright | bright.png | 73.887 |
| 0.5020 | Blurry | flat_mid.png | 0 |
| 0.5971 | OK | portrait.png | 201.51 |
| 0.5170 | OK | wide_banner.png | 2909.27 |
| 0.5925 | OK | photo_a.jpg | 1481.37 |
| 0.5011 | OK | photo_b.jpg | 8914.04 |
| 0.4901 | OK | photo_c.jpg | 10461.76 |
| 0.8435 | OK | plain.jpg | 230.68 |
| 0.4903 | OK | gray.jpg | 18698.44 |
| 0.5003 | OK | stripes_fine_copy.jpg | 22509.03 |
View data
| Format | Height (px) | File | Width (px) |
|---|---|---|---|
| PNG | 48 | gradient_a.png | 64 |
| PNG | 48 | gradient_a_copy.png | 64 |
| PNG | 48 | gradient_a_near.png | 64 |
| PNG | 40 | gradient_b.png | 80 |
| PNG | 64 | stripes_fine.png | 64 |
| PNG | 64 | stripes_blurred.png | 64 |
| PNG | 50 | stripes_wide.png | 90 |
| PNG | 60 | checker.png | 60 |
| PNG | 32 | checker_gray.png | 48 |
| PNG | 40 | checker_alpha.png | 40 |
| PNG | 36 | palette.png | 36 |
| PNG | 40 | dark.png | 60 |
| PNG | 40 | bright.png | 60 |
| PNG | 30 | flat_mid.png | 30 |
| PNG | 90 | portrait.png | 40 |
| PNG | 20 | wide_banner.png | 120 |
| JPEG | 48 | photo_a.jpg | 64 |
| JPEG | 56 | photo_b.jpg | 56 |
| JPEG | 48 | photo_c.jpg | 72 |
| JPEG | 40 | plain.jpg | 40 |
| JPEG | 48 | gray.jpg | 48 |
| JPEG | 64 | stripes_fine_copy.jpg | 64 |
View data
| Flag | File | PC 1 | PC 2 |
|---|---|---|---|
| OK | gradient_a.png | 0.7091 | 2.310 |
| Duplicate | gradient_a_copy.png | 0.7091 | 2.310 |
| Duplicate | gradient_a_near.png | 0.7096 | 2.295 |
| OK | gradient_b.png | −2.834 | 0.6196 |
| OK | stripes_fine.png | −0.0566 | −1.913 |
| OK | stripes_blurred.png | −0.1064 | −1.341 |
| OK | stripes_wide.png | 1.954 | 0.8558 |
| OK | checker.png | 0.6090 | −1.846 |
| OK | checker_gray.png | 0.1656 | −1.966 |
| OK | checker_alpha.png | −6.833 | 0.3521 |
| Blurry | palette.png | −5.269 | 2.574 |
| Dark | dark.png | −10.389 | −1.554 |
| Bright | bright.png | 10.204 | −0.4908 |
| Blurry | flat_mid.png | −0.1527 | −1.524 |
| OK | portrait.png | 2.244 | 2.898 |
| OK | wide_banner.png | −0.3354 | 0.6315 |
| OK | photo_a.jpg | 1.766 | 1.773 |
| OK | photo_b.jpg | −0.2190 | −0.4322 |
| OK | photo_c.jpg | −0.2570 | −0.5075 |
| OK | plain.jpg | 7.662 | −1.198 |
| OK | gray.jpg | −0.2377 | −1.765 |
| OK | stripes_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
| File | Flag | Brightness | Sharpness | Duplicate group |
|---|---|---|---|---|
| gradient_a_copy.png | Duplicate | 0.5459 | 111.35 | 1 |
| gradient_a_near.png | Duplicate | 0.5458 | 138.60 | 1 |
| palette.png | Blurry | 0.2885 | 73.680 | 0 |
| dark.png | Dark | 0.0469 | 73.171 | 0 |
| bright.png | Bright | 0.9604 | 73.887 | 0 |
| flat_mid.png | Blurry | 0.5020 | 0 | 0 |
Cameras (EXIF)
| Make and model | Images |
|---|---|
| Fixturecam FX-100 | 1 |
| Fixturecam FX-200 | 1 |
| Othercam O-1 | 1 |
- 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"))
))
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
| File | Flag | Brightness | Sharpness | Duplicate group |
|---|---|---|---|---|
| gradient_a_copy.png | Duplicate | 0.5459 | 111.35 | 1 |
| gradient_a_near.png | Duplicate | 0.5458 | 138.60 | 1 |
| palette.png | Blurry | 0.2885 | 73.680 | 0 |
| dark.png | Dark | 0.0469 | 73.171 | 0 |
| bright.png | Bright | 0.9604 | 73.887 | 0 |
| flat_mid.png | Blurry | 0.5020 | 0 | 0 |
Cameras (EXIF)
| Make and model | Images |
|---|---|
| Fixturecam FX-100 | 1 |
| Fixturecam FX-200 | 1 |
| Othercam O-1 | 1 |
- 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.
Resizing changes the picture
PredictPredict first
A 640 × 480 photo of a round plate is stretched to 224 × 224. What happens to the plate?
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.
Three ways to get a square
ReadMost 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.
Splits come before crops
ReadPhotos 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:
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
View data
| Brightness (0–1) | Flag | File | Sharpness (variance of the Laplacian) |
|---|---|---|---|
| 0.3951 | Blurry | good_00.png | 1.052 |
| 0.3771 | Blurry | good_01.png | 1.499 |
| 0.3765 | Blurry | good_02.png | 1.568 |
| 0.3952 | Blurry | good_03.png | 1.093 |
| 0.3771 | Blurry | good_04.png | 1.489 |
| 0.3765 | Blurry | good_05.png | 1.537 |
| 0.3952 | Blurry | good_06.png | 1.049 |
| 0.3768 | Blurry | good_07.png | 1.490 |
| 0.3764 | Blurry | good_08.png | 1.537 |
| 0.3954 | Blurry | good_09.png | 1.079 |
| 0.3772 | Blurry | good_10.png | 1.481 |
| 0.3766 | Blurry | good_11.png | 1.505 |
| 0.3954 | Blurry | good_12.png | 1.076 |
| 0.3770 | Blurry | good_13.png | 1.519 |
| 0.3767 | Blurry | good_14.png | 1.517 |
| 0.3957 | Blurry | good_15.png | 1.057 |
| 0.3775 | Blurry | good_16.png | 1.571 |
| 0.3766 | Blurry | good_17.png | 1.542 |
| 0.3953 | Blurry | good_18.png | 1.049 |
| 0.3774 | Blurry | good_19.png | 1.570 |
| 0.3766 | Blurry | good_20.png | 1.498 |
| 0.3953 | Blurry | good_21.png | 1.073 |
| 0.3763 | Blurry | good_22.png | 1.516 |
| 0.3769 | Blurry | good_23.png | 1.576 |
| 0.3952 | Blurry | good_24.png | 1.089 |
| 0.3772 | Blurry | good_25.png | 1.495 |
| 0.3763 | Blurry | good_26.png | 1.522 |
| 0.3951 | Blurry | good_27.png | 1.077 |
| 0.3770 | Blurry | good_28.png | 1.554 |
| 0.3766 | Blurry | good_29.png | 1.565 |
| 0.3959 | Blurry | good_30.png | 1.051 |
| 0.3769 | Blurry | good_31.png | 1.529 |
| 0.3765 | Blurry | good_32.png | 1.515 |
| 0.3955 | Blurry | good_33.png | 1.074 |
| 0.3770 | Blurry | good_34.png | 1.513 |
| 0.3765 | Blurry | good_35.png | 1.528 |
| 0.3952 | Blurry | good_36.png | 1.059 |
| 0.3766 | Blurry | good_37.png | 1.535 |
| 0.3766 | Blurry | good_38.png | 1.516 |
| 0.3955 | Blurry | good_39.png | 1.063 |
| 0.3771 | Blurry | good_40.png | 1.522 |
| 0.3765 | Blurry | good_41.png | 1.556 |
| 0.3955 | Blurry | good_42.png | 1.049 |
| 0.3768 | Blurry | good_43.png | 1.521 |
| 0.3763 | Blurry | good_44.png | 1.512 |
| 0.3952 | Blurry | good_45.png | 1.042 |
| 0.3770 | Blurry | good_46.png | 1.518 |
| 0.3762 | Blurry | good_47.png | 1.555 |
| 0.3958 | Blurry | good_48.png | 1.041 |
| 0.3772 | Blurry | good_49.png | 1.506 |
| 0.3765 | Blurry | good_50.png | 1.530 |
| 0.3955 | Blurry | good_51.png | 1.085 |
| 0.3768 | Blurry | good_52.png | 1.535 |
| 0.3765 | Blurry | good_53.png | 1.513 |
| 0.3957 | Blurry | good_54.png | 1.063 |
| 0.3769 | Blurry | good_55.png | 1.522 |
| 0.3767 | Blurry | good_56.png | 1.544 |
| 0.3954 | Blurry | good_57.png | 1.062 |
| 0.3766 | Blurry | good_58.png | 1.517 |
| 0.3765 | Duplicate | good_59.png | 1.546 |
First 60 of 74 rows.
View data
| Height (px) | File | Width (px) |
|---|---|---|
| 32 | good_00.png | 32 |
| 32 | good_01.png | 40 |
| 40 | good_02.png | 32 |
| 32 | good_03.png | 32 |
| 32 | good_04.png | 40 |
| 40 | good_05.png | 32 |
| 32 | good_06.png | 32 |
| 32 | good_07.png | 40 |
| 40 | good_08.png | 32 |
| 32 | good_09.png | 32 |
| 32 | good_10.png | 40 |
| 40 | good_11.png | 32 |
| 32 | good_12.png | 32 |
| 32 | good_13.png | 40 |
| 40 | good_14.png | 32 |
| 32 | good_15.png | 32 |
| 32 | good_16.png | 40 |
| 40 | good_17.png | 32 |
| 32 | good_18.png | 32 |
| 32 | good_19.png | 40 |
| 40 | good_20.png | 32 |
| 32 | good_21.png | 32 |
| 32 | good_22.png | 40 |
| 40 | good_23.png | 32 |
| 32 | good_24.png | 32 |
| 32 | good_25.png | 40 |
| 40 | good_26.png | 32 |
| 32 | good_27.png | 32 |
| 32 | good_28.png | 40 |
| 40 | good_29.png | 32 |
| 32 | good_30.png | 32 |
| 32 | good_31.png | 40 |
| 40 | good_32.png | 32 |
| 32 | good_33.png | 32 |
| 32 | good_34.png | 40 |
| 40 | good_35.png | 32 |
| 32 | good_36.png | 32 |
| 32 | good_37.png | 40 |
| 40 | good_38.png | 32 |
| 32 | good_39.png | 32 |
| 32 | good_40.png | 40 |
| 40 | good_41.png | 32 |
| 32 | good_42.png | 32 |
| 32 | good_43.png | 40 |
| 40 | good_44.png | 32 |
| 32 | good_45.png | 32 |
| 32 | good_46.png | 40 |
| 40 | good_47.png | 32 |
| 32 | good_48.png | 32 |
| 32 | good_49.png | 40 |
| 40 | good_50.png | 32 |
| 32 | good_51.png | 32 |
| 32 | good_52.png | 40 |
| 40 | good_53.png | 32 |
| 32 | good_54.png | 32 |
| 32 | good_55.png | 40 |
| 40 | good_56.png | 32 |
| 32 | good_57.png | 32 |
| 32 | good_58.png | 40 |
| 40 | good_59.png | 32 |
First 60 of 74 rows.
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
| Row | File | Flag | Brightness | Sharpness |
|---|---|---|---|---|
| 1 | good_00.png | Blurry | 0.3951 | 1.052 |
| 2 | good_01.png | Blurry | 0.3771 | 1.499 |
| 3 | good_02.png | Blurry | 0.3765 | 1.568 |
| 4 | good_03.png | Blurry | 0.3952 | 1.093 |
| 5 | good_04.png | Blurry | 0.3771 | 1.489 |
| 6 | good_05.png | Blurry | 0.3765 | 1.537 |
| 7 | good_06.png | Blurry | 0.3952 | 1.049 |
| 8 | good_07.png | Blurry | 0.3768 | 1.490 |
| 9 | good_08.png | Blurry | 0.3764 | 1.537 |
| 10 | good_09.png | Blurry | 0.3954 | 1.079 |
| 11 | good_10.png | Blurry | 0.3772 | 1.481 |
| 12 | good_11.png | Blurry | 0.3766 | 1.505 |
| 13 | good_12.png | Blurry | 0.3954 | 1.076 |
| 14 | good_13.png | Blurry | 0.3770 | 1.519 |
| 15 | good_14.png | Blurry | 0.3767 | 1.517 |
| 16 | good_15.png | Blurry | 0.3957 | 1.057 |
| 17 | good_16.png | Blurry | 0.3775 | 1.571 |
| 18 | good_17.png | Blurry | 0.3766 | 1.542 |
| 19 | good_18.png | Blurry | 0.3953 | 1.049 |
| 20 | good_19.png | Blurry | 0.3774 | 1.570 |
| 21 | good_20.png | Blurry | 0.3766 | 1.498 |
| 22 | good_21.png | Blurry | 0.3953 | 1.073 |
| 23 | good_22.png | Blurry | 0.3763 | 1.516 |
| 24 | good_23.png | Blurry | 0.3769 | 1.576 |
| 25 | good_24.png | Blurry | 0.3952 | 1.089 |
| 26 | good_25.png | Blurry | 0.3772 | 1.495 |
| 27 | good_26.png | Blurry | 0.3763 | 1.522 |
| 28 | good_27.png | Blurry | 0.3951 | 1.077 |
| 29 | good_28.png | Blurry | 0.3770 | 1.554 |
| 30 | good_29.png | Blurry | 0.3766 | 1.565 |
| 31 | good_30.png | Blurry | 0.3959 | 1.051 |
| 32 | good_31.png | Blurry | 0.3769 | 1.529 |
| 33 | good_32.png | Blurry | 0.3765 | 1.515 |
| 34 | good_33.png | Blurry | 0.3955 | 1.074 |
| 35 | good_34.png | Blurry | 0.3770 | 1.513 |
| 36 | good_35.png | Blurry | 0.3765 | 1.528 |
| 37 | good_36.png | Blurry | 0.3952 | 1.059 |
| 38 | good_37.png | Blurry | 0.3766 | 1.535 |
| 39 | good_38.png | Blurry | 0.3766 | 1.516 |
| 40 | good_39.png | Blurry | 0.3955 | 1.063 |
First 40 of 50 rows.
Copies and near-duplicates
| Kind | Row | File | Row | Copy | Bits apart | Split | Copy's split |
|---|---|---|---|---|---|---|---|
| identical | 4 | good_03.png | 73 | good_03_copy.png | 0 | train | test |
| near | 6 | good_05.png | 74 | good_05_edit.png | 0 | train | test |
| near | 30 | good_29.png | 60 | good_59.png | 6 | train | test |
Sources on both sides of the split
| Source | Training images | Held-out images |
|---|---|---|
| cam2 | 19 | 5 |
Quality by label
| label | Images | Mean brightness | Mean contrast | Median sharpness | Flagged |
|---|---|---|---|---|---|
| defect | 4 | 0.3721 | 0.1416 | 2.000 | 4 |
| good | 70 | 0.3789 | 0.1465 | 1.513 | 70 |
- 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"))
))
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
| Row | File | Flag | Brightness | Sharpness |
|---|---|---|---|---|
| 1 | good_00.png | Blurry | 0.3951 | 1.052 |
| 2 | good_01.png | Blurry | 0.3771 | 1.499 |
| 3 | good_02.png | Blurry | 0.3765 | 1.568 |
| 4 | good_03.png | Blurry | 0.3952 | 1.093 |
| 5 | good_04.png | Blurry | 0.3771 | 1.489 |
| 6 | good_05.png | Blurry | 0.3765 | 1.537 |
| 7 | good_06.png | Blurry | 0.3952 | 1.049 |
| 8 | good_07.png | Blurry | 0.3768 | 1.490 |
| 9 | good_08.png | Blurry | 0.3764 | 1.537 |
| 10 | good_09.png | Blurry | 0.3954 | 1.079 |
| 11 | good_10.png | Blurry | 0.3772 | 1.481 |
| 12 | good_11.png | Blurry | 0.3766 | 1.505 |
| 13 | good_12.png | Blurry | 0.3954 | 1.076 |
| 14 | good_13.png | Blurry | 0.3770 | 1.519 |
| 15 | good_14.png | Blurry | 0.3767 | 1.517 |
| 16 | good_15.png | Blurry | 0.3957 | 1.057 |
| 17 | good_16.png | Blurry | 0.3775 | 1.571 |
| 18 | good_17.png | Blurry | 0.3766 | 1.542 |
| 19 | good_18.png | Blurry | 0.3953 | 1.049 |
| 20 | good_19.png | Blurry | 0.3774 | 1.570 |
| 21 | good_20.png | Blurry | 0.3766 | 1.498 |
| 22 | good_21.png | Blurry | 0.3953 | 1.073 |
| 23 | good_22.png | Blurry | 0.3763 | 1.516 |
| 24 | good_23.png | Blurry | 0.3769 | 1.576 |
| 25 | good_24.png | Blurry | 0.3952 | 1.089 |
| 26 | good_25.png | Blurry | 0.3772 | 1.495 |
| 27 | good_26.png | Blurry | 0.3763 | 1.522 |
| 28 | good_27.png | Blurry | 0.3951 | 1.077 |
| 29 | good_28.png | Blurry | 0.3770 | 1.554 |
| 30 | good_29.png | Blurry | 0.3766 | 1.565 |
| 31 | good_30.png | Blurry | 0.3959 | 1.051 |
| 32 | good_31.png | Blurry | 0.3769 | 1.529 |
| 33 | good_32.png | Blurry | 0.3765 | 1.515 |
| 34 | good_33.png | Blurry | 0.3955 | 1.074 |
| 35 | good_34.png | Blurry | 0.3770 | 1.513 |
| 36 | good_35.png | Blurry | 0.3765 | 1.528 |
| 37 | good_36.png | Blurry | 0.3952 | 1.059 |
| 38 | good_37.png | Blurry | 0.3766 | 1.535 |
| 39 | good_38.png | Blurry | 0.3766 | 1.516 |
| 40 | good_39.png | Blurry | 0.3955 | 1.063 |
First 40 of 50 rows.
Copies and near-duplicates
| Kind | Row | File | Row | Copy | Bits apart | Split | Copy's split |
|---|---|---|---|---|---|---|---|
| identical | 4 | good_03.png | 73 | good_03_copy.png | 0 | train | test |
| near | 6 | good_05.png | 74 | good_05_edit.png | 0 | train | test |
| near | 30 | good_29.png | 60 | good_59.png | 6 | train | test |
Sources on both sides of the split
| Source | Training images | Held-out images |
|---|---|---|
| cam2 | 19 | 5 |
Quality by label
| label | Images | Mean brightness | Mean contrast | Median sharpness | Flagged |
|---|---|---|---|---|---|
| defect | 4 | 0.3721 | 0.1416 | 2.000 | 4 |
| good | 70 | 0.3789 | 0.1465 | 1.513 | 70 |
- 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"}],
})
Watch a leak happen
ExploreThe 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?
The pipeline
Commit your prediction above to see the result
Make your prediction to see the result.
What runs in CodeSplash
ReadCheck: images as data
CheckpointCheck 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.
Show the answer
The order:
- Group images by source and split the groups
- Resize the way the pretrained model expects
- Augment the training images only
- 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.
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