CodeSampleX

Sample

pillow 12.3.0: PIL.ImageStat, PIL.ImageStat.Stat

Verified sample for pypi pillow 12.3.0: PIL.ImageStat, PIL.ImageStat.Stat. The contract ran on python 3.12 · linux alpine/x64 · docker and passed.

sha256:ad6f70e8f722c1bb320d20b8e74813deeb5b16d82b7f8a33edee2f414880db52

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment python 3.12 linux x64 python 3.12 python pip

Verification-run environments

Environment Contract Stages Run
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

Case

HOW
Goal
verify PIL.ImageStat in pkg:pypi/pillow@12.3.0
Packages
Symbols
  • PIL.ImageStat
  • PIL.ImageStat.Stat
Environment
python 3.12
Created
2026-08-28T04:20:54Z

Contract

  1. PIL.ImageStat.Stat computes per-band pixel count, extrema, sum, and sum of squares for an image.
  2. PIL.ImageStat.Stat calculates mean, root mean square, variance, and standard deviation statistical metrics per channel.
  3. PIL.ImageStat.Stat accepts a binary or grayscale mask to restrict statistical evaluation to non-zero regions.
  4. PIL.ImageStat.Stat can be instantiated from an image histogram list directly.

Files

  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/image_statistics.py
  • test/contract.py

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify PIL.ImageStat in pkg:pypi/pillow@12.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pillow@12.3.0
Demonstrate these symbols/APIs:
  - PIL.ImageStat
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:9e606fdffdd32e2b2d5a5beb4e7be7e9a4fe7c4e8c9f6e112b6c9e71e700657c","contract":["PIL.ImageStat.Stat computes per-band pixel count, extrema, sum, and sum of squares for an image.","PIL.ImageStat.Stat calculates mean, root mean square, variance, and standard deviation statistical metrics per channel.","PIL.ImageStat.Stat accepts a binary or grayscale mask to restrict statistical evaluation to non-zero regions.","PIL.ImageStat.Stat can be instantiated from an image histogram list directly."],"goal":"verify PIL.ImageStat in pkg:pypi/pillow@12.3.0","kind":"HOW","packages":["pkg:pypi/pillow@12.3.0"],"schemaVersion":1,"symbols":["PIL.ImageStat","PIL.ImageStat.Stat"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pillow@12.3.0"],"schemaVersion":1,"subject":"pkg:pypi/pillow@12.3.0","symbols":["PIL.ImageStat","PIL.ImageStat.Stat"],"verifierAdapter":"python@1"}
requirements.txt
pillow==12.3.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify PIL.ImageStat in pkg:pypi/pillow@12.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pillow@12.3.0"
  ],
  "symbols": [
    "PIL.ImageStat"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/image_statistics.py
"""Image statistics module demonstrating PIL.ImageStat functionality."""

from typing import List, Optional, Tuple, Union
from PIL import Image, ImageStat


def get_image_stats(
    image_or_histogram: Union[Image.Image, List[int]],
    mask: Optional[Image.Image] = None,
) -> ImageStat.Stat:
    """Calculate statistical metrics for an image or histogram.

    Args:
        image_or_histogram: PIL Image object or a histogram list.
        mask: Optional mask image (mode '1' or 'L') restricting pixels to analyze.

    Returns:
        PIL.ImageStat.Stat instance containing computed statistics.
    """
    return ImageStat.Stat(image_or_histogram, mask=mask)


def get_channel_means(
    image: Image.Image,
    mask: Optional[Image.Image] = None,
) -> List[float]:
    """Calculate the average pixel value for each channel.

    Args:
        image: PIL Image object.
        mask: Optional mask image.

    Returns:
        List of average pixel values per channel.
    """
    stat = ImageStat.Stat(image, mask=mask)
    return stat.mean


def get_channel_extrema(
    image: Image.Image,
    mask: Optional[Image.Image] = None,
) -> List[Tuple[int, int]]:
    """Calculate the minimum and maximum pixel values for each channel.

    Args:
        image: PIL Image object.
        mask: Optional mask image.

    Returns:
        List of (min, max) tuples for each channel.
    """
    stat = ImageStat.Stat(image, mask=mask)
    return stat.extrema


def get_channel_stddev(
    image: Image.Image,
    mask: Optional[Image.Image] = None,
) -> List[float]:
    """Calculate the standard deviation for each channel.

    Args:
        image: PIL Image object.
        mask: Optional mask image.

    Returns:
        List of standard deviation values per channel.
    """
    stat = ImageStat.Stat(image, mask=mask)
    return stat.stddev
test/contract.py
"""Contract verification test for PIL.ImageStat in pkg:pypi/pillow@12.3.0."""

import math
import os
import sys

# Ensure repository root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import PIL
from PIL import Image, ImageStat
from src.image_statistics import (
    get_channel_extrema,
    get_channel_means,
    get_channel_stddev,
    get_image_stats,
)


def test_symbol_presence_and_version():
    assert PIL.__version__ == "12.3.0", f"Expected Pillow 12.3.0, got {PIL.__version__}"
    assert hasattr(PIL, "ImageStat")
    assert hasattr(ImageStat, "Stat")


def test_grayscale_statistics():
    # Create a 2x2 grayscale (L) image with values [10, 20, 30, 40]
    im = Image.new("L", (2, 2))
    im.putpixel((0, 0), 10)
    im.putpixel((1, 0), 20)
    im.putpixel((0, 1), 30)
    im.putpixel((1, 1), 40)

    stat = ImageStat.Stat(im)

    # Pixel count per band
    assert stat.count == [4]

    # Min and max pixel values
    assert stat.extrema == [(10, 40)]

    # Sum of pixel values: 10 + 20 + 30 + 40 = 100.0
    assert stat.sum == [100.0]

    # Sum of squared pixel values: 100 + 400 + 900 + 1600 = 3000.0
    assert stat.sum2 == [3000.0]

    # Mean: 100.0 / 4 = 25.0
    assert stat.mean == [25.0]

    # Root mean square: sqrt(3000.0 / 4) = sqrt(750.0)
    assert math.isclose(stat.rms[0], math.sqrt(750.0), rel_tol=1e-6)

    # Variance: (3000.0 - (100.0^2 / 4)) / 4 = 125.0
    assert math.isclose(stat.var[0], 125.0, rel_tol=1e-6)

    # Standard deviation: sqrt(125.0)
    assert math.isclose(stat.stddev[0], math.sqrt(125.0), rel_tol=1e-6)


def test_multiband_rgb_statistics():
    # Create a 2x1 RGB image
    # Pixel (0, 0): (10, 50, 100)
    # Pixel (1, 0): (30, 70, 200)
    im = Image.new("RGB", (2, 1))
    im.putpixel((0, 0), (10, 50, 100))
    im.putpixel((1, 0), (30, 70, 200))

    stat = ImageStat.Stat(im)

    # Count across 3 bands
    assert stat.count == [2, 2, 2]

    # Extrema across R, G, B channels
    assert stat.extrema == [(10, 30), (50, 70), (100, 200)]

    # Sums: R=40.0, G=120.0, B=300.0
    assert stat.sum == [40.0, 120.0, 300.0]

    # Sum of squares: R=1000.0, G=7400.0, B=50000.0
    assert stat.sum2 == [1000.0, 7400.0, 50000.0]

    # Means: R=20.0, G=60.0, B=150.0
    assert stat.mean == [20.0, 60.0, 150.0]

    # Variance: R=100.0, G=100.0, B=2500.0
    assert math.isclose(stat.var[0], 100.0, rel_tol=1e-6)
    assert math.isclose(stat.var[1], 100.0, rel_tol=1e-6)
    assert math.isclose(stat.var[2], 2500.0, rel_tol=1e-6)

    # Standard deviation: R=10.0, G=10.0, B=50.0
    assert math.isclose(stat.stddev[0], 10.0, rel_tol=1e-6)
    assert math.isclose(stat.stddev[1], 10.0, rel_tol=1e-6)
    assert math.isclose(stat.stddev[2], 50.0, rel_tol=1e-6)


def test_masked_statistics():
    # Create 2x2 grayscale image with pixels [10, 20, 30, 40]
    im = Image.new("L", (2, 2))
    im.putpixel((0, 0), 10)
    im.putpixel((1, 0), 20)
    im.putpixel((0, 1), 30)
    im.putpixel((1, 1), 40)

    # Mask selecting only (0, 0) and (1, 1) -> pixels 10 and 40
    mask = Image.new("L", (2, 2), color=0)
    mask.putpixel((0, 0), 255)
    mask.putpixel((1, 1), 255)

    stat = ImageStat.Stat(im, mask=mask)

    # Only 2 masked pixels counted
    assert stat.count == [2]
    assert stat.extrema == [(10, 40)]
    assert stat.sum == [50.0]
    assert stat.sum2 == [1700.0]
    assert stat.mean == [25.0]
    # Variance: (1700 - (2500 / 2)) / 2 = (1700 - 1250) / 2 = 225.0
    assert math.isclose(stat.var[0], 225.0, rel_tol=1e-6)
    assert math.isclose(stat.stddev[0], 15.0, rel_tol=1e-6)


def test_histogram_instantiation():
    im = Image.new("L", (2, 2))
    im.putpixel((0, 0), 10)
    im.putpixel((1, 0), 20)
    im.putpixel((0, 1), 30)
    im.putpixel((1, 1), 40)

    hist = im.histogram()
    stat_from_hist = ImageStat.Stat(hist)
    stat_direct = ImageStat.Stat(im)

    assert stat_from_hist.count == stat_direct.count
    assert stat_from_hist.extrema == stat_direct.extrema
    assert stat_from_hist.sum == stat_direct.sum
    assert stat_from_hist.sum2 == stat_direct.sum2
    assert stat_from_hist.mean == stat_direct.mean


def test_helper_module():
    im = Image.new("RGB", (2, 1))
    im.putpixel((0, 0), (10, 50, 100))
    im.putpixel((1, 0), (30, 70, 200))

    means = get_channel_means(im)
    assert means == [20.0, 60.0, 150.0]

    extrema = get_channel_extrema(im)
    assert extrema == [(10, 30), (50, 70), (100, 200)]

    stddevs = get_channel_stddev(im)
    assert math.isclose(stddevs[0], 10.0, rel_tol=1e-6)
    assert math.isclose(stddevs[1], 10.0, rel_tol=1e-6)
    assert math.isclose(stddevs[2], 50.0, rel_tol=1e-6)

    stat = get_image_stats(im)
    assert isinstance(stat, ImageStat.Stat)


def main():
    test_symbol_presence_and_version()
    test_grayscale_statistics()
    test_multiband_rgb_statistics()
    test_masked_statistics()
    test_histogram_instantiation()
    test_helper_module()
    print("CONTRACT PASS: PIL.ImageStat in Pillow 12.3.0")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Origin Seeder

anonymous