8000 fix(plugin-hash): exclude DC term from pHash average and composite alpha onto grey by hipstersmoothie · Pull Request #1466 · jimp-dev/jimp · GitHub
[go: up one dir, main page]

Skip to content

fix(plugin-hash): exclude DC term from pHash average and composite alpha onto grey - #1466

Merged
hipstersmoothie merged 2 commits into
mainfrom
sesh/make-phash-respect-alpha-1221
Nov 23, 2026
Merged

hipstersmoothie merged 2 commits into
mainfrom
sesh/make-phash-respect-alpha-1221

Conversation

@hipstersmoothie
Copy link
Copy Markdown
Collaborator

Fixes #1221, fixes #338

Warning

This changes the pHash of every image, opaque ones included. Any hashes users have stored (for de-duplication, look-ups and so on) won't match hashes computed after this change. Whether that calls for a major or a minor bump, and a changelog note, is the maintainer's call.

What's Changing and Why

Two fixes in plugins/plugin-hash/src/phash.ts, one commit each.

1. Exclude the DC term from the average (#338)

The comment in getHash says the DC coefficient dctVals[0][0] is left out of the mean because it "can be significantly different from the other values and will throw off the average", but the loop summed it anyway. On bright, low-contrast images such as sketches and line art, the DC term dominated the average, so every other bit came out 0. Different images then all hashed to 1000…0 (80000000000 in base 64), with a distance of 0 between them.

The fix skips x === 0 && y === 0 when summing and divides by smallerSize * smallerSize - 1. The hash is still 64 bits.

All five images attached to #338 hashed to 1000…0 before. They now get distinct hashes, with pairwise distances of 0.41–0.64.

2. Composite transparent pixels onto mid-grey before hashing (#1221)

pHash never looked at alpha. Transparency was only handled incidentally by the default resize step, which:

  • turns fully transparent pixels black, whatever RGB is hidden under them;
  • leaves partially transparent pixels at full colour, ignoring their alpha;
  • is skipped entirely for images that are already 32×32, so the hidden RGB goes straight into the DCT.

So every dark shape on a transparent background hashed the same, and a 32×32 image's hash depended on pixels you can't see. A 32×32 white ring with black vs. white hidden under the transparent pixels scored a distance of 0.42 on main.

This PR composites a clone of the image onto opaque grey (128) before resizing. Opaque pixels are skipped, so this commit on its own leaves opaque images' hashes unchanged: only dice.png, the one fixture with alpha, changes. The caller's image is not modified.

Why grey and not white?

White would match how diff (pixelmatch) blends, but it erases white-on-transparent content. Black, which is effectively what main does today, erases dark content. Measured with both commits applied:

Background #1221 icons White square vs. white bar on transparent Black square vs. black bar on transparent 32×32 ring, black vs. white hidden RGB
main (no composite) 0.219 0.469 0 0.422
White (255) 0 (both icons become blank) 0 0.344 0
Grey (128), this PR 0.297 0.344 0.344 0
Black (0) 0.297 0.344 0 0

The background is one constant, FLATTEN_BACKGROUND in phash.ts, if you'd rather use a different one.

About the icons in #1221

The two icons are white glyphs (a circled ×) on a transparent background, and both have black RGB under the transparent pixels. So hidden RGB wasn't what made them differ. main was effectively comparing white-on-black shapes. Shown side by side they are the same symbol with different padding and stroke weight, and a 64-bit pHash of thin line art is sensitive to that.

After this PR they score 0.30, not ~0. That reflects real shape and stroke differences, not a bug. The only background that gets them to 0 is white, and it does so by erasing both icons to blank images. With white, every white-on-transparent image would hash the same. What this PR fixes from #1221 is the underlying problem: hashes that depend on invisible pixels and on how alpha happens to pass through resize.

What else might be affected

Tasks

  • Add tests
    • Some images have 0 hash. #338: two thin-line sketches on white (a cross and a frame). They fail on main (the cross hashes to 1000…0, distance 0.047) and pass now (0.906).
    • Whether phash is calculated correctly #1221: the hidden colour under transparent pixels (black, white, noise) doesn't change the hash, at 32px and 64px. The 32px case fails on main.
    • Whether phash is calculated correctly #1221: light and dark shapes on transparent backgrounds stay distinguishable. This fails on main for dark shapes, and would fail with a white background for light shapes.
    • pHash() doesn't modify the caller's image.
    • The Some images have 0 hash. #338 attachments aren't committed as fixtures: they're about 1 MB in total and were uploaded by third parties. I verified against them locally.
  • Update Documentation: n/a, no API change
  • Update jimp.d.ts: n/a
  • Add SemVer Label: left to the maintainer (see above)

pnpm build, pnpm lint and pnpm test all pass, rebased onto current main.

🤖 Generated with Claude Code

hipstersmoothie and others added 2 commits November 22, 2026 22:38
The comment in getHash says the DC coefficient is left out of the mean
because it can be much larger than the other values, but the loop summed
it anyway. On bright images with little contrast (sketches, line art) the
DC term dominated the average, so every AC bit came out 0 and different
images all hashed to 1000...0 (`80000000000` in base 64), with a distance
of 0 between them.

Skip dctVals[0][0] when summing and divide by smallerSize^2 - 1. The hash
is still 64 bits.

This changes the pHash of every image, opaque ones included, so the
expected hashes in the tests are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng (#1221)

pHash never looked at alpha. Transparency was only handled incidentally by
the resize step: fully transparent pixels came out black, partially
transparent pixels kept their full colour, and images that were already
32x32 skipped resampling, so whatever RGB sat under transparent pixels
went straight into the DCT. As a result, every dark shape on a
transparent background hashed the same, and the hash of a 32x32 image
depended on pixels you can't see.

Composite a clone of the image onto opaque mid-grey (128) before resizing.
Grey, rather than white or black, keeps both light and dark shapes on a
transparent background visible. Opaque pixels are skipped, so images
without alpha hash exactly as before. The caller's image is not modified.

Only dice.png has alpha among the fixtures, so only its expected hashes
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie
hipstersmoothie merged commit a12fcf0 into main Nov 23, 2026
5 checks passed
@hipstersmoothie
hipstersmoothie deleted the sesh/make-phash-respect-alpha-1221 branch November 23, 2026 06:49
@hipstersmoothie hipstersmoothie added the major Increment the major version when merged label Nov 23, 2026
hipstersmoothie added a commit that referenced this pull request Nov 24, 2026
* docs: Kid Studio redesign with full method reference and playgrounds (WIP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: register sharpen, toColorSpace, otsuThreshold and the Color Spaces guide

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: register skew, affine, exposure, vibrance and the Migrate to v2 guide

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update effects and compositing pages for 2.0

Add the sharpen page and playground op. Document dither's type and
palette options, convolute/convolution divisor, bias, preserveAlpha
and even-sized kernels, blur/gaussian radius changes, region clamping
in pixelate, convolute and blit, composite across Jimp classes with
clamped opacity and the new blend-mode error, mask luminance and alpha,
centered shadow size, and invalid boxShadow colors. Remove the cautions
for bugs fixed in 2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: replace obsolete gotchas in WRITING.md with version-note guidance

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update size, shape and transform pages for 2.0; add skew and affine

- New skew and affine method pages with playgrounds (#1515)
- resize/scale/scaleToFit: LANCZOS, LANCZOS2, MITCHELL (#1481),
  premultiplyAlpha (#1502), default resizer premultiplies (#1499),
  rounding fix
- cover/contain: { x, y } fractional align (#1513), missing axis centered
  and stricter flag validation (#1499), premultiplyAlpha
- crop: clamps to the image and throws for empty regions (#1501, #1511)
- autocrop/autocropRect: ignoreSides/leaveBorder with cropOnlyFrames,
  transparent pixels match (#1499)
- rotate: centered rotation and new canvas size (#1490), ResizeStrategy
  modes interpolate (#1508)
- circle radius 0, border invalid colors throw, displace alpha/stretched
  map and offset { x, y } (#1499, #1497, #1514)
- Playground: rotate interpolation modes, fractional align for
  cover/contain, displace y offset, new skew and affine ops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update color, pixel and constants pages for 2.0

- color(): multiply action, CSS colors in mix/multiply/xor, greyscale action
  matching greyscale(), ColorActionName exported, changed saturate/lighten maths
- new pages: exposure(), vibrance(), otsuThreshold()
- sepia(amount), threshold max "otsu" and per-channel autoGreyscale:false,
  contrast around 127.5, posterize nearest level, normalize flat channels,
  greyscale rounding, quantize colors validation
- pixels: setPixelColor ignores off-image points, NaN throws, Edge.WRAP any
  distance, Edge as a runtime export, scan/scanIterator region clamping
- concepts: color spaces section, Edge and ColorActionName, new
  ResizeStrategy members, JimpMime.ico, align rules, exported type names
- playground: exposure, vibrance and otsuThreshold ops, multiply action,
  sepia amount, threshold otsu toggle, getPixelIndex uses Edge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update text, comparison and errors pages for 2.0

- print: box layout from x/y, alignment without maxWidth/maxHeight,
  whole-word wrapping, kept blank lines, cb position (#1498, #1505)
- loadFont: HTTP/fetch errors, non-PNG page errors, bundled font coverage
  (#1475, #1498, #1509)
- measureText/measureTextHeight: widest line, optional maxWidth, empty lines
- hash/pHash/distance/distanceFromHash: options added in 2.0, hashes
  differ from 1.x (#1466, #1472)
- compareHashes: base argument, decodes hash() output (#1499)
- diff: options object, DiffColor, dark diff example (#1510)
- errors-and-validation: re-verified every message; colors, regions,
  ENOENT, ICO/BMP/SVG errors (#1497, #1501, #1503, #1506, #1518, #1522)
- playground: alignment without a box, blank-line preset, diffMask,
  diffColor and alpha controls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update loading, saving, formats and color space pages for 2.0

- read/fromBuffer: Uint8Array/Blob input, ENOENT for missing files,
  exifRotate and ReadOptions
- fromBitmap/new Jimp: data is copied and length-checked, colorSpace,
  invalid colors throw
- getBuffer/write: icc option, BMP bitPP, ICO, per-extension option
  typing; remove dead BMP/PNG options; PNG bitDepth 16 is broken
- clone copies mime, background and ICC profile
- New toColorSpace page; cssColorToHex throws and takes color()
- Formats: ICO, JPEG 2000, SVG, strict WASM options, community
  plugins (jimp-heic)
- Guides: Color Spaces restyle, exifRotate, JPEG 2000 and SVG sections
  with bundler notes, corrected JPEG memory limits, browser fonts path
  and fromBitmap copying, ICO in defaults, Node 22
- Playground encode op gains ICO; webp-example casts around the
  wasm-webp declaration bug

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: write the Migrate to v2 guide and update guides and home for 2.0

- guides/migrate-to-v2: every breaking change merged for 2.0 (Node 22,
  errors that now throw, behavior changes, removed options, types), with
  before/after code checked against 1.7.0 and the 2.0 build, plus a
  "New in 2.0" section linking the new methods, options and formats
- guides/migrate-to-v1: point to the v2 guide; note Edge is a runtime
  export only since 2.0 and that opaque PNGs drop alpha automatically
- guides/getting-started: Node.js 22, Jimp.read path vs URL rules and
  input types, ENOENT for missing files, new WASM formats
- guides/writing-plugins: the format detect() hook, color spaces in
  plugins (CSS colors, keeping iccProfile on new canvases), 2.0 versions
- home and methods index: sharpen and roundCorners in the playground,
  ICO and the new WASM formats in the feature copy, 2.0 methods in the
  section intros

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: flag stored-hash incompatibility and add #1357 and morphology to the v2 guide

- Caution near the top: pHash/hash values differ for every image in 2.0,
  so 1.x hashes can't be compared with 2.0 hashes; re-hash stored images
- Hashes section explains the degenerate 1.x hashes and cross-version
  compareHashes/distanceFromHash
- Jimp.read now passes decode options for file paths and buffers (#1357)
- New in 2.0: erode, dilate, open and close (#1523)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: add erode, dilate, open and close method pages

Document @jimp/plugin-morphology (#1523): four method pages with
scanned-document cleanup, mask, outline and ink examples, playground
ops with radius and shape controls, and method entries under Blur &
effects. Link the new pages from the v2 migration guide, threshold and
dither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie
Copy link
Copy Markdown
Collaborator Author

🚀 PR was released in v2.0.0 🚀

@hipstersmoothie hipstersmoothie added the released This issue/pull request has been released. label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

major Increment the major version when merged released This issue/pull request has been released.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Whether phash is calculated correctly Some images have 0 hash.

1 participant

0