DEV Community

Jay
Jay

Posted on

A chroma step edge is never one pixel wide after 4:2:0 — and the decoder does the widening

I spent a day trying to answer a question that sounded trivial: when a marketplace re-encodes my product photo with 4:2:0 chroma subsampling, how much of the cutout edge does it eat?

The trivial answer is "some". The measured answer turned out to be more specific, and it moved the blame somewhere I did not expect. On a boundary that falls exactly on a chroma sample boundary, the subsampling itself costs nothing. The stored colours come back exact. The two-pixel ramp that shows up in the decoded file is produced entirely by the decoder's upsampling filter.

That is not a rounding-error distinction. It changes what you can do about it, because the two costs have different remedies and different sizes depending on where your edge happens to land.

Here is the whole measurement, with the fixtures that make each number checkable.

The pipeline, and the one stage under test

A JPEG encoder for a colour image does this:

RGB -> YCbCr -> subsample Cb,Cr -> 8x8 DCT + quantise -> entropy code -> file
Enter fullscreen mode Exit fullscreen mode

4:2:0 means the two chroma planes are stored at half resolution in both directions. 4:2:2 halves only horizontally. 4:4:4 stores all three planes at full resolution.

Four of those five stages are not what I want to measure, so I held them fixed by holding the encoder fixed: Pillow over libjpeg, one quality, one image, only the subsampling argument changing. Pillow's argument is an integer — 0, 1, 2 — and I did not take the docstring's word for what it does. Reading the SOF0 marker out of the produced files:

4:4:4: SOF0 components (h,v) = [(1, 17), (2, 17), (3, 17)]
4:2:2: SOF0 components (h,v) = [(1, 33), (2, 17), (3, 17)]
4:2:0: SOF0 components (h,v) = [(1, 34), (2, 17), (3, 17)]
Enter fullscreen mode Exit fullscreen mode

Those are hex-ish byte pairs: luma sampling factor 0x11 at 4:4:4, 0x21 at 4:2:2, 0x22 at 4:2:0, with both chroma components at 0x11. So the parameter is doing what it says.

The other thing I checked before trusting a single-variable comparison: whether changing subsampling also changes the quantisation tables. It does not, at least not here.

q95  4:4:4  luma sum 369   chroma sum 558
q95  4:2:0  luma sum 369   chroma sum 558
q85  4:4:4  luma sum 1109  chroma sum 1666
q85  4:2:0  luma sum 1109  chroma sum 1666
Enter fullscreen mode Exit fullscreen mode

Byte-identical tables. That matters, because if the encoder had quietly softened the chroma quantiser for 4:4:4 then "4:4:4 is better at the same quality" would be measuring two things at once and the comparison would be worthless. It is one thing.

Fixture one: an image with nothing to subsample

The first test is not about the encoder. It is about the meter, and it exists so that every later number has a floor.

Take a real product photo, throw away its colour, re-encode at q85 in all three configurations.

greyscale source, nothing for the chroma grid to hold:
  4:4:4  dE  0.388  dC  0.000   10334 bytes
  4:2:2  dE  0.388  dC  0.000    9874 bytes
  4:2:0  dE  0.388  dC  0.000    9747 bytes
Enter fullscreen mode Exit fullscreen mode

dC is the mean absolute change in chroma; dE is CIEDE2000. On a greyscale image the chroma planes are flat, so the subsampling has literally nothing to average, and the chroma error is exactly 0.000 at all three settings — while the file still gets 6% smaller. The dE of 0.388 is identical in all three, which is the tell: that number is luma quantisation, untouched by the chroma stage.

If a chroma metric reports a cost on a greyscale image, it is measuring luma. Mine does not, which is the only reason I kept using it.

Fixture two: a step in chroma and nothing else

Two flat fields, same lightness, different hue, meeting at a hard vertical boundary:

def chroma_step(w=192, h=128, edge=None, vertical=True,
                left=(55.0, 45.0, 20.0), right=(55.0, -35.0, 35.0)):
    ...
Enter fullscreen mode Exit fullscreen mode

Identical L*, different a* and b*. Luma is constant everywhere, so luma quantisation cannot move the boundary, and any change across it has to be the chroma stage.

Now the measurement. I want a number that is the width of the transition, not a threshold count, because an integer count of a continuous thing flaps. The one I used:

effective width = 1 / sum of squared pixel-to-pixel steps, normalised
Enter fullscreen mode Exit fullscreen mode

A hard edge scores 1.00. The same total change spread over two equal steps scores 2.00; over four, 4.00. No tolerance, so no pixel can land on the wrong side of one.

Run that on the decoded file, at the boundary position that falls on the chroma grid (x=96, even) and one pixel off it (x=97, odd, halfway through a 2x2 chroma sample):

edge runs vertically  (varies along x), at pixel 96:
  4:4:4  width x  1.00 px
  4:2:2  width x  2.60 px
  4:2:0  width x  2.60 px
edge runs vertically  (varies along x), at pixel 97:
  4:4:4  width x  1.09 px
  4:2:2  width x  4.33 px
  4:2:0  width x  4.40 px
Enter fullscreen mode Exit fullscreen mode

So: 4:4:4 keeps a step. 4:2:0 turns it into a ramp of 2.6 pixels or 4.4 pixels depending on phase, and 4:2:2 is already at the 4:2:0 value on a vertical edge, because a vertical edge varies horizontally, which is the direction 4:2:2 halves.

And the direction check, which is what stops a single isotropic number from faking any of this — same fixture rotated, so the chroma now varies down the image instead of across it:

edge runs horizontally (varies along y), at pixel 96:
  4:4:4  y 1.00 px    4:2:2  y 1.00 px    4:2:0  y 2.60 px
edge runs horizontally (varies along y), at pixel 97:
  4:4:4  y 1.09 px    4:2:2  y 1.09 px    4:2:0  y 4.42 px
Enter fullscreen mode Exit fullscreen mode

4:2:2 is a complete no-op on a horizontal edge and full strength on a vertical one. 4:2:0 hits both. That asymmetry is a property of the format, not of my measurement, and it is the cheapest way to check that a subsampling test is testing subsampling.

Splitting the bill: what the file did, and what the decoder did

The 2.6 and 4.4 above are totals. Two stages contribute to them and only one of them is in the file.

So I built the encoder by hand — box-average the chroma planes to half resolution, put them back — with no DCT and no quantisation, and tried two reconstruction rules:

  • replicate: each stored sample is copied to the 2x2 pixels it covers. This is the minimum any decoder could do.
  • triangle: libjpeg's "fancy" upsampler, out[2k] = (3s[k] + s[k-1]) / 4 and out[2k+1] = (3s[k] + s[k+1]) / 4.
edge along x, at 96:  replicate  1.00 px   triangle  2.57 px   libjpeg  2.60 px
edge along x, at 97:  replicate  2.02 px   triangle  4.49 px   libjpeg  4.40 px
edge along y, at 96:  replicate  1.00 px   triangle  2.57 px   libjpeg  2.60 px
edge along y, at 97:  replicate  2.02 px   triangle  4.49 px   libjpeg  4.42 px
Enter fullscreen mode Exit fullscreen mode

The triangle row lands on libjpeg's real output to within a few hundredths, which is the check that the hand-built encoder is actually the thing I claim it is. And now the split is explicit:

  • Aligned boundary: the container costs 0.00 px. The whole 1.60 px of excess is the decode filter. The stored chroma values are exactly right; the decoder is what declines to reproduce them as a step.
  • Half-sample boundary: 1.02 px is the box average losing the transition, and 2.38 px is the filter again.

You can see it in the pixel values directly. Source a* across the edge, then what comes back:

source             [44.9  44.9  44.9  44.9  -34.98 -34.98 -34.98 -34.98 -34.98]
replication 2x2    [44.9  44.9  44.9  44.9  -34.98 -34.98 -34.98 -34.98 -34.98]
triangle    2x2    [44.9  44.9  44.9  25.72 -16.13 -34.98 -34.98 -34.98 -34.98]
libjpeg     4:2:0  [44.81 44.81 44.81 24.80 -16.67 -35.32 -35.32 -35.32 -35.32]
Enter fullscreen mode Exit fullscreen mode

Replication is exact. The triangle decoder emits 0.24 and 0.76 of the way across the transition at two adjacent pixels — the signature of convolving a step with a 1-3-1 kernel. libjpeg's real output is 0.25 and 0.77. The 4:2:0 file did not contain a ramp; it contains two chroma values and nothing else, and the ramp is manufactured at display time.

Four curves across the same chroma boundary, at two boundary positions. The 4:4:4 encode keeps a step, replicating the stored chroma samples keeps a step at the aligned position, and both the triangle filter and the real libjpeg output produce a two- or four-pixel ramp.

This is why "4:2:0 halves your chroma resolution" is simultaneously true and misleading. It halves the sampled resolution. What reaches your eyes is that, run back through a low-pass filter that is wider than the grid, so you get roughly a quarter of the chroma resolution in width terms and you cannot get the subsampling back without also getting the filter back.

The grid that matters is not the grid in the tutorials

4:2:0 is usually described in terms of 16x16 pixel blocks, which makes it sound as though a boundary aligned to that grid would be safe. That number is the DCT block — 8x8 chroma coefficients covering 16x16 pixels — and it is the wrong grid for this question.

An edge has to survive the sample grid, which at 4:2:0 is one chroma sample per 2x2 pixels. I walked the boundary one pixel at a time across 17 positions and measured the decoded width:

edge phase  4:4:4   4:2:2   4:2:0
  88    0     1.00    2.75    2.83
  89    1     1.09    4.56    4.53
  90    0     1.11    2.58    2.59
  91    1     1.00    4.66    4.63
  92    0     1.09    2.69    2.82
  93    1     1.01    4.63    4.59
  ...
  96    0     1.00    2.60    2.60
  97    1     1.09    4.33    4.40
Enter fullscreen mode Exit fullscreen mode

The period is 2, not 16. Nothing special happens at phase 0 or phase 8; every even pixel behaves one way and every odd pixel behaves a worse way. Across the 17 positions the even rows land in 2.56 to 2.83 and the odd rows in 4.33 to 4.70, while the 4:4:4 control jitters between 1.00 and 1.11 — that jitter is luma quantisation bleeding into the a* line I sample, and it is the noise floor for the whole table.

Aligning a product edge to a 16-pixel grid therefore buys nothing at all. You would need to align it to a 2-pixel grid, which means choosing the parity of the boundary, which is not a design decision anyone can make on purpose.

Now the same question on 16 real product photos

Synthetic steps are countable but they are not photographs. So: 16 covers from a working article pipeline, resized to 640 px wide, each encoded at three qualities and three sampling settings, error measured against the untouched PNG inside a subject mask.

The mask is deliberately crude — median border colour, CIEDE2000 distance above 12, plus a 3-pixel dilation/erosion band as "the edge" — and identical for every configuration, so its crudeness is shared and cannot be part of the difference between rows.

Means over the 16 photos at q85 (dE whole subject, dE_edge the boundary band, dC chroma, dH chroma-weighted hue rotation, in degrees):

config dE dE_edge dC dH bytes
4:4:4 1.243 1.393 0.741 2.444 44,849
4:2:2 1.346 1.543 0.891 2.736 40,306
4:2:0 1.433 1.689 1.026 2.905 37,850

At q95 and q75 the pattern holds with slightly different magnitudes: edge error goes 0.963 -> 1.228 at q95 and 1.736 -> 2.021 at q75 for 4:4:4 -> 4:2:0. So the cost of 4:2:0 is +21% on the edge at q85 for 15.6% fewer bytes, and the edge is hit harder than the image as a whole: dE rises 15.3%, dE_edge 21.2%.

The per-photo spread is wide, and worth knowing before anyone quotes a single multiplier:

4:2:0 ratio of edge error vs 4:4:4:  range 1.00x to 1.68x, median 1.17x
  worst   remove-bg-vs-pixelcut-vs-picviva-2026   1.322 -> 2.222
  best    dropshipping-product-images-supplier-photos  0.910 -> 0.911
Enter fullscreen mode Exit fullscreen mode

One photo is unaffected; another's edge error grows 68%. "Chroma subsampling costs you about a fifth of your edge accuracy" is a median with a range wide enough to be useless for a single image — which is why the mechanism matters more than the average.

At the same file size, subsampling is a bad trade

The comparison above holds the encoder's quality setting equal. That is not the comparison a person shipping a file actually has. They have a byte budget. So the interesting question is: given 38 KB, is it better spent on 4:4:4 at a lower quality, or on 4:2:0 at a higher one?

Bisect the 4:4:4 quality until its file is no bigger than the 4:2:0 file (match to within 2%):

q 4:4:4 quality needed bytes dE_edge vs 4:2:0 at the same size
95 92.8 66,435 1.082 1.228
85 78.9 37,222 1.593 1.689
75 64.4 28,175 1.974 2.021

4:4:4 wins at every size. The price is a quality drop of 2.2 points at q95, 6.1 at q85 and 10.6 at q75 — the more you have already compressed, the more quality you have to surrender to buy the 15–17% of bytes back. Expressing it as a rate:

q95: subsampling is 2.23x as expensive per byte saved as lowering the quality
q85: 1.48x
q75: 1.20x
Enter fullscreen mode Exit fullscreen mode

The trend is the interesting part. At high quality the chroma grid is the binding constraint and losing it is expensive; at q75 luma quantisation has already destroyed so much that the two options converge. If you are shipping at q85 or above, 4:2:0 is not a good deal. If you are already at q70 because the marketplace caps you at 100 KB, the argument mostly disappears — which is also why the folklore "4:2:0 is fine, nobody can see it" is sometimes true and never for the reason given.

Checking the mechanism without a mask

Everything above depends on a mask, and a mask is a place to hide a mistake. So here is the same damage measured with no mask, no boundary detection, and no threshold: bucket every pixel with meaningful chroma by how fast the chroma was changing in the original, and average the error per bucket.

If subsampling damages edges because a half-resolution grid cannot hold a fast change, the error has to rise with the gradient. If it is flat, my story is wrong.

bin (flattest 12.5% first):
  4:4:4             0.492  0.552  0.611  0.675  0.754  0.830  0.956  1.444
  4:2:0             0.645  0.726  0.811  0.906  1.044  1.173  1.385  2.305
  ratio 4:2:0/4:4:4  1.31   1.31   1.33   1.34   1.38   1.41   1.45   1.60
Enter fullscreen mode Exit fullscreen mode

Both curves rise, because JPEG is lossy everywhere and steeper chroma is harder to code at any sampling ratio. The ratio is what isolates subsampling, and it rises monotonically: 1.31x on flat chroma, 1.60x on the steepest twelfth. The extra cost is concentrated exactly where the grid is thinnest.

Mean chroma error against the local chroma gradient of the original. All three curves rise, and the 4:2:0 curve rises faster: the ratio of 4:2:0 error to 4:4:4 error goes from 1.31 on the flattest bin to 1.60 on the steepest.

That is the mechanism, confirmed on 15 of the 16 photos (one was excluded by the binning guard: only 4.1% of its frame is subject, too few high-gradient pixels to fill the last bucket).

The part I did not expect: the platform's re-encode dominates

Nothing in the previous sections decides what a buyer sees, because nobody ships one encode. A seller exports, the marketplace ingests and re-encodes, and that second file is the one on the page.

So: seven uploads, each pushed once through the same marketplace-style pass (q82, 4:2:0), error measured against the original PNG both before and after.

upload bytes dE_edge before dE_edge after the pass added
png 233 KB 0.000 1.786 —
4:4:4 q95 82 KB 0.963 1.806 +87%
4:4:4 q85 44 KB 1.393 1.867 +34%
4:2:2 q85 39 KB 1.543 1.894 +23%
4:2:0 q95 68 KB 1.228 1.854 +51%
4:2:0 q85 37 KB 1.689 1.890 +12%
4:2:0 q70 25 KB 2.143 2.274 +6%

Two things fall out of that table.

First, the losses are not additive, they overlap. The platform pass charges a pristine 4:4:4 q95 export 87%, and an already-4:2:0 q85 export only 12%, because most of what it would remove has already been removed. Uploading the best possible file does not get you the best possible output; it gets you 1.806, which is within 1.1% of what an untouched PNG would have produced (1.786) and 4.4% better than uploading a 4:2:0 q85 file, which is the file that would otherwise sit on the page.

Second, the choice you control is worth a few percent, and the choice you do not control is worth tens. Across all seven uploads the final edge error spans 1.786 to 2.274 — 27% — and six of those seven sit inside 6% of each other. Meanwhile the single re-encode in the middle of every chain, which you have no say in, is worth more than any of it.

Dumbbell chart: seven upload settings, each with its edge error before and after one q82 4:2:0 re-encode. The seven different starting points converge into a narrow band. A second panel shows chroma error across four repeated saves at a fixed setting versus a chain that changes setting each time.

The practical reading: stop optimising your export for a platform that is going to overwrite it, and check what the platform actually does instead, because that is the stage with the leverage.

Re-saving is nearly free, until you change a setting

The last thing I wanted to know is what happens on the second and third pass, because "every save loses quality" is repeated constantly and I wanted a number.

Same file, four passes, chroma error against the untouched PNG:

chain             pass 1   pass 2   pass 3   pass 4    total
82 x4              1.072    1.088    1.095    1.099     +2.5%
90 x4              0.943    0.967    0.982    0.991     +5.1%
82,90,75,82        1.072    1.120    1.287    1.320    +23.2%
Enter fullscreen mode Exit fullscreen mode

Passes two to four at a fixed setting add 1.6% / 0.6% / 0.4% of the first pass's cost, converging. The quantised coefficients map onto themselves, so re-encoding at the setting that produced the file lands back on nearly the same coefficients. Four saves are not four times the loss; they are about 1.02 times it.

Change the setting between passes and it starts over. Pass three of 82, 90, 75, 82 — the one after the quality drops to 75 — adds 15.6% of the first pass's cost on its own.

So the folklore is wrong in its mechanism and right in its conclusion, which is the worst combination. Re-saving is not what accumulates. Re-saving differently is. A workflow that touches a file five times at one setting is fine. A workflow that touches it twice at two settings is not.

What I would actually do

Given all of the above, and being honest that it is calibrated on one encoder:

  1. Find out whether the platform re-encodes at all, and at what. If it does not, upload the best file you can and stop reading. If it does, its settings are the dominant term and your export is a rounding decision.
  2. Do not use 4:2:0 as a size lever at q85 or above. At equal bytes, 4:4:4 is better on the edge at every quality I tested, and the price is two to eleven quality points — cheap at the top of the range, expensive at the bottom. Subsampling is only competitive once you are already deep into low quality.
  3. If you must use it, know that the container is not the whole cost. At q85 the edge error goes from 1.393 to 1.689; the box average accounts for part of that and the decode filter for the rest, and on an aligned boundary the box average accounts for none of it. You cannot buy the filter's share back with more chroma samples — the only thing that removes it is 4:4:4.
  4. Do not bother aligning product edges to a block grid. The period is 2 pixels, not 16. Aligning to 2 pixels means controlling boundary parity, which nobody can do deliberately.
  5. Export once, at the setting you will keep. Repeated identical saves cost about 2%, repeated different saves cost 20%+.

What this does not cover

  • One encoder. Pillow over libjpeg(-turbo). mozjpeg, libvips/sharp, and the various CDN encoders pick their own upsampler and their own chroma quantisation, so the split between "container" and "decoder" will move — the aligned-edge result in particular is a property of the triangle filter, and a decoder using nearest-neighbour would show the 1.00 px figure instead.
  • One colour space. sRGB in, YCbCr out, no ICC handling. Wide-gamut input will hit different chroma quantisation.
  • A 640 px working width. At full marketplace resolution the 2-pixel grid is a smaller fraction of the subject, so absolute dE_edge values will move; the mechanism will not.
  • A coarse mask. CIEDE2000 > 12 from the border median is not a segmentation model. It is identical across every row of every table, which is what the comparison needs, and it is why I also report the mask-free gradient table.
  • dE_edge is not perceptual importance. A ramp on the outside of a product's outline is often less visible than the same ramp across a printed logo inside it. Everything here is measured on pixel neighbourhoods, not on what a person notices.

Reproducing it

Five files, all of them plain numpy and Pillow:

  • subsample.py — the fixtures, the hand-built encoder, and the instrument checks in validate(). Run it first; if the greyscale chroma error is not 0.000, or the triangle row does not land on libjpeg, nothing after it means anything.
  • subsample_run.py — the 16-photo matrix, pinned by name and sha256 in subsample_photos.json so the corpus cannot drift out from under the numbers.
  • subsample_cascade.py — the marketplace-pass comparison and the equal-bytes bisection.
  • subsample_chain.py — the repeated-save chains.
  • subsample_report.py — every figure quoted above, printed from the JSON.

The pinning is not fussiness. My first run of the matrix and my first run of the cascade picked different photos, because the cover corpus grew between them, and for a while two tables in this piece were describing two different sets of images.


I work on the image pipeline at PicViva, which is where I ran into this: the export-and-upload step is ours, the ingest-and-re-encode step belongs to the marketplace, and it took a while to work out which of the two was costing the edge. The short version is that it is usually not the one I can fix in our code.

Top comments (0)