Skip to content

ADescribe · describe.image_quality

Image quality and duplicate audit

Are these images usable — exposure, contrast, blur, sizes — and are there copies or leaks across the split?

Profiles an image collection from the images themselves: brightness, contrast, colorfulness and sharpness (variance of the Laplacian) on one analysis copy per image, size and aspect-ratio distributions when the collection records pixel sizes, and three perceptual hashes (aHash, dHash, pHash). Byte-identical files (same content hash) and near-duplicates (hashes a few bits apart) are listed in pairs; with a split column it lists held-out images that copy a training image, and with a source column the cameras, patients or sessions that appear on both sides of the split. Dark, bright and blurry images are flagged against thresholds you set. Runs on the decoded copies the app makes once per collection, identically in Python and R.

Experimental Python and R agree to 6 decimals Also called image quality, blur detection, variance of the Laplacian…

A real result

Example “Parts defaults”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Image quality and duplicate auditRecorded · Python and R agreeRecorded 2026-11-25 · 33 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.

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 apart
identical4good_03.png73good_03_copy.png0
near6good_05.png74good_05_edit.png0
near30good_29.png60good_59.png6
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
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 apart
identical4good_03.png73good_03_copy.png0
near6good_05.png74good_05_edit.png0
near30good_29.png60good_59.png6
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Parts defaultsimg2_parts · image: path
  • Parts split source sizesimg2_parts · height: height · image: path · label: label · source: source · split: split · width: width
  • Parts dhash strictimg2_parts · image: path · split: split
  • Parts ahashimg2_parts · image: path · label: label
  • Degenerate all naimg2_parts · image: path
  • Degenerate n1img2_parts · image: path

In the guides

Where it sits in the decision guides

  • Type: structured (tabular), unstructured (text, images, audio, video), time series / sequential, graph / relational · DS & ML Decision Guide · Key data characteristics — what influences method choice
  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize

What you need

Image pathcategorical · 1 column
A column of image file paths, such as a media collection's path column.
Compare bycategorical / boolean · 0–1 column · 1–30 levels
Optional: a class or folder column; quality is summarized for each of its values.
Splitcategorical · 0–1 column · 2–9 levels
Optional: a column marking images train, valid or test; copies across it are listed.
Sourcecategorical · 0–1 column · 1–100000 levels
Optional: the camera, patient or session of each image; sources on both sides of the split are listed.
Width (px)numeric · 0–1 column
Optional: each file's pixel width, as a media collection records it, for the size and shape charts.
Height (px)numeric · 0–1 column
Optional: each file's pixel height, as a media collection records it.

Choices you make

statistics

Dark belowdefault 0.15

Images whose mean brightness (0–1) is below this are flagged dark.

Bright abovedefault 0.85

Images whose mean brightness (0–1) is above this are flagged bright (washed out).

Blurry belowdefault 100

Variance of the Laplacian below this flags an image as blurry. Plain, flat images score low too.

Near-duplicates bydefault phash

Which perceptual hash decides near-duplicates; all three are saved.

  • pHash (DCT)(default) — Low-frequency DCT pattern; robust to resizing, re-encoding and small edits.
  • dHash (gradients) — Left-to-right brightness changes; fast and robust to exposure shifts.
  • aHash (average) — 8 × 8 thumbnail against its mean; the simplest, most easily fooled.
Near-duplicate distancedefault 6

Hashes that differ in at most this many of 64 bits count as near-duplicates.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Measured on a 256 × 256 copy

    Every image is resized to 256 × 256 (stretched) before measuring, so sharpness compares images at one scale.

  • Sharpness depends on content

    The Laplacian variance falls when an image is plain or soft as well as blurred; compare images of similar subjects.

  • Similar scenes are not copies

    Near-duplicate pairs can be different shots of a near-identical scene (inspection lines, burst photos); look at the pairs before removing any.

What it reports

n_rows
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_images
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_no_path
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_unreadable
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
brightness_mean
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
brightness_sd
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
contrast_mean
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
colorfulness_mean
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
saturation_mean
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
sharpness_median
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
entropy_mean
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_dark
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_bright
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_blurry
Brightness, contrast, colorfulness, saturation, sharpness and entropy measured on one 256 × 256 copy of each image.
n_exact_copies
Pairs of images that are the same file (same content hash) or a few hash bits apart; groups join pairs that share an image.
n_exact_groups
Pairs of images that are the same file (same content hash) or a few hash bits apart; groups join pairs that share an image.
n_near_pairs
Pairs of images that are the same file (same content hash) or a few hash bits apart; groups join pairs that share an image.
n_near_groups
Pairs of images that are the same file (same content hash) or a few hash bits apart; groups join pairs that share an image.
n_in_near_groups
Pairs of images that are the same file (same content hash) or a few hash bits apart; groups join pairs that share an image.
n_train
Held-out (valid or test) images that are identical to, or near copies of, a training image.
n_held_out
Held-out (valid or test) images that are identical to, or near copies of, a training image.
n_cross_exact
Held-out (valid or test) images that are identical to, or near copies of, a training image.
n_cross_near
Held-out (valid or test) images that are identical to, or near copies of, a training image.
n_sources
Cameras, patients or sessions with images on both sides of a split; their images look alike, so scores overstate new-source accuracy.
n_groups_across
Cameras, patients or sessions with images on both sides of a split; their images look alike, so scores overstate new-source accuracy.
width_median
Width, height and width ÷ height of the original files, as the media collection recorded them.
height_median
Width, height and width ÷ height of the original files, as the media collection recorded them.
aspect_median
Width, height and width ÷ height of the original files, as the media collection recorded them.
share_portrait
Width, height and width ÷ height of the original files, as the media collection recorded them.
megapixels_median
Width, height and width ÷ height of the original files, as the media collection recorded them.
n_sizes
Width, height and width ÷ height of the original files, as the media collection recorded them.
hash
64-bit fingerprints: dHash notes whether each pixel of a tiny copy is brighter than its left neighbor, aHash whether it beats the mean.
threshold
64-bit fingerprints: dHash notes whether each pixel of a tiny copy is brighter than its left neighbor, aHash whether it beats the mean.

Per group, level or term: group_n[<level>], group_brightness[<level>], group_sharpness[<level>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, pandas, codesplash; R uses nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines read the same decoded copies (float32 tensor shards from the sidecar) and run the same twins (codesplash.images.hashes / features ↔ R/images_hashes.R / R/images.R). Measures differ only by matrix-product rounding; hash comparisons use a 1e-9 tie margin so both engines set the same bits.
  • Outside the app (exported code) the files are decoded by codesplash.media.decode ↔ cs_media_decode_image; without the collection's content hashes, identical files are found by path.
Python

The exact script CodeSplash ran for example “Parts defaults” · 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 4c250e903a4c2feb
# 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 = None
SPLIT = None
SOURCE = None
WIDTH = None
HEIGHT = None
_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_defaults/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_defaults/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"}],
})
R

The exact script CodeSplash ran for example “Parts defaults” · 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 4c250e903a4c2feb
# 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 <- NULL
SPLIT <- NULL
SOURCE <- NULL
WIDTH <- NULL
HEIGHT <- NULL
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_defaults/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_defaults/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"))
))

Sources

  • Pech-Pacheco JL, Cristóbal G, Chamorro-Martínez J, Fernández-Valdivia J (2000). Diatom autofocusing in brightfield microscopy: a comparative study. ICPR 2000, 314–317.
  • Hasler D, Süsstrunk S (2003). Measuring colourfulness in natural images. Proc. SPIE 5007, Human Vision and Electronic Imaging VIII.
  • Zauner C (2010). Implementation and benchmarking of perceptual image hash functions. Master's thesis, Upper Austria University of Applied Sciences.
  • Krawetz N (2013). Kind of like that. The Hacker Factor Blog (difference hash), 21 January 2013.
  • Kapoor S, Narayanan A (2023). Leakage and the reproducibility crisis in machine-learning-based science. Patterns 4(9):100804.

From the CodeSplash method registry · describe.image_quality v1.0.0.