Halfway Between Black and White Is Not sRGB 128

Choose black and white as two image values. The integer halfway between their eight-bit channel codes is about 128. But if “halfway” means an equal-weight average in linear light, the encoded sRGB result rounds to 188. These are different operations on different representations. This lesson lets you calculate both and deliberately switch between them.

sRGB means standard red, green and blue: a defined RGB colour space with a nonlinear transfer function. RGB is the three-channel red, green and blue representation. A transfer function maps a channel between its encoded number and a normalized linear-light coordinate. The latter is proportional to that channel's light contribution within the specified model. It is not a claim about how bright a particular screen looks.

Outcome: decode two in-gamut sRGB values, average with a declared weight, encode the result, and explain why code 188 is neither an exact half nor a universal perceptual midpoint. All data and colours below are constructed. No screen calibration or physical light measurement was performed.

Materials and the two meanings of average

Use a computer with Python, the supplied reader files, and a text editor. Optional paper and a calculator help you predict the values first. No microcontroller, sensor or calibrated display is required. CSV means comma-separated values, the tabular text format used for the generated ramp. The complete program uses only the Python standard library. Actual host execution used CPython 3.9.6 (CPython is the reference implementation of Python); that old interpreter is recorded as execution evidence, not recommended for deployment. Use a currently supported Python installation for your own environment; only the recorded host version was exercised here.

Let C be an encoded channel and L a linear-light channel, both normalized to the closed interval 0 to 1. A weight t is the fraction assigned to the right endpoint; 1−t belongs to the left. Encoding is a representation choice, not random measurement noise. In particular, the word gamma is often used loosely for this relationship, but the exact sRGB curve has a straight branch near zero as well as a power branch.

Use the exact branches, then quantize once

The World Wide Web Consortium (W3C) specification supplies the sRGB conversion branches. For the nonnegative, in-gamut values used here:

decode(C) = C / 12.92                       when C ≤ 0.04045
          = ((C + 0.055) / 1.055)^2.4        otherwise

encode(L) = 12.92 L                         when L ≤ 0.0031308
          = 1.055 L^(1 / 2.4) − 0.055       otherwise

encoded average = (1−t) C_left + t C_right
linear average  = encode((1−t) decode(C_left) + t decode(C_right))
8-bit code      = floor(255 × encoded value + 0.5)

The last line declares nearest rounding with ties upward. It differs from Python's default tie-to-even round. Keep normalized values until this final step. The program deliberately rejects out-of-gamut values rather than silently clipping them; signed extensions, alpha compositing, gamut conversion and high dynamic range imagery are outside this experiment.

sRGB decoding curve showing encoded 0.5 below linear light 0.5, which encodes to about 0.735357.
Original constructed transfer/geometry figure. Pan the diagram on a narrow screen, or open the full vector figure.

With endpoints 0 and 1 and t = 0.5, encoded averaging produces C = 0.5. Its decoded light coordinate is approximately 0.214041. Linear-light averaging instead gives L = 0.5, which encodes to C = 0.7353569830524495. Multiplying by 255 gives approximately 187.516, which rounds to 188. An actual eight-bit code 128 is 128/255, not exactly 0.5, and decodes to approximately 0.2158605001. Code 188 decodes to approximately 0.5028864580. Quantization explains why that final number is slightly above one half.

Predict, run, change one thing, restore

  1. Copy the reader directory and open a terminal there. Enter predictions for weights 0, 0.25, 0.5, 0.75 and 1 in data/blank-observations.csv. Leave its observation cells blank until you run the calculation.
  2. Run python3 -m unittest discover -s code -v, then python3 code/srgb_lab.py --output my-run. The new directory contains result.json, a 257-row ramp.csv and a lossless patches.png. Rows are calculations, not samples from hardware.
  3. Find the CSV row with weight 0.5. The encoded red, green and blue columns should all be 128; the linear-light columns should all be 188. Check the endpoints: both methods return black at weight 0 and white at weight 1.
  4. Inject the representation fault by treating the encoded average as a linear-light average. Compare its decoded value with the required 0.5. The fault is the operation order; the arithmetic has not become noisy.
  5. Run python3 code/srgb_lab.py --output red-blue --left 1,0,0 --right 0,0,1. The centre codes are (128, 0, 128) and (188, 0, 188). Restore the original black and white command and check that its original result returns.
  6. Try weight 0.25 and then a pair of identical endpoint colours. Identical colours should stay effectively unchanged, allowing for floating-point precision and final rounding. Try --weight nan: it must fail before creating the requested output directory.
Constructed gray ramps and red-blue patches compare averaging encoded channels with averaging decoded linear-light channels.
Original calculated comparison; no measured data. Pan the diagram on a narrow screen, or open the full vector figure.

What the controls establish

The same endpoints and weights isolate the representation choice. The all-256-code round-trip test checks that decoding and re-encoding preserves each eight-bit code after the declared rounding. Independent 60-digit decimal calculations check selected power-branch values. Tests also cover asymmetric weights, complementary swaps, endpoints, malformed channel shapes and nonfinite inputs.

The published branch constants are rounded. At the encode join they produce a tiny downward mismatch of roughly 2.85 × 10−8; the test suite checks that mismatch instead of asserting exact continuity or analytic monotonicity everywhere. A finite ordered grid and all eight-bit codes pass their declared checks. The 4 × 10−8 normalized round-trip tolerance is a numerical check, not a calibration uncertainty or a physical error bound.

Actual host execution passed 23 tests. This establishes the listed calculations for the bundled implementation on that host. A displayed patch additionally depends on image colour handling, the display, ambient conditions and the viewer. Looking at the patches cannot establish calibrated luminance, equal perceived brightness or a measured mixture of real light sources.

Challenge and worked answer

Suppose two people both report “I averaged the red and blue endpoints.” Can the resulting code alone tell you whether they used the same operation? Predict both centre values, and explain why averaging the resulting eight-bit numbers again would lose information.

Worked answer

The encoded-channel centre is (128, 0, 128); decode-average-encode gives (188, 0, 188). The endpoint values and colour space must accompany the claimed average. Quantized codes discard fractional information, so repeated rounding is not equivalent to retaining normalized coordinates and quantizing once. Neither numeric result establishes which patch an observer will call halfway.

Follow the representation question further

Resistor colour bands also turn a visual representation into a number, but use a discrete code. This lesson instead isolates a nonlinear numeric encoding. Statistical filtering and covariance are separate questions: a perfectly repeatable encoded average can still implement the wrong intended operation.

Primary sources and source conditions

Sources were checked on November 30, 2026. Figures, calculations, lesson text and experiment code are original work for this lesson. Linked third-party material is not bundled in the reader.

Complete reproducible code and checks

Both complete files below are also supplied as editable reader files. Commands create new local output directories. PNG means Portable Network Graphics; SVG means Scalable Vector Graphics. These original figure formats preserve the constructed diagrams; the explanatory text remains Hypertext Markup Language (HTML).

srgb_lab.py — complete file
"""In-gamut sRGB arithmetic; all outputs are constructed, never measurements."""
import argparse
import csv
import json
import math
from pathlib import Path
import struct
import zlib

def unit(value):
    if isinstance(value,bool) or not isinstance(value,(int,float)):
        raise ValueError('expected a real number in [0, 1]')
    try: value=float(value)
    except (OverflowError,ValueError): raise ValueError('number out of range')
    if not math.isfinite(value) or not 0<=value<=1:
        raise ValueError('expected a finite number in [0, 1]')
    return value

def decode_srgb(value):
    c=unit(value)
    return c/12.92 if c<=0.04045 else ((c+0.055)/1.055)**2.4

def encode_srgb(value):
    light=unit(value)
    return 12.92*light if light<=0.0031308 else 1.055*light**(1/2.4)-0.055

def quantize8(value):
    # Explicit half-up rule, unlike Python round's tie-to-even rule.
    return min(255,int(math.floor(unit(value)*255+0.5)))

def color(value):
    if not isinstance(value,(tuple,list)) or len(value)!=3:
        raise ValueError('expected three normalized sRGB channels')
    return tuple(unit(c) for c in value)

def mix_encoded(left,right,weight):
    a,b,t=color(left),color(right),unit(weight)
    return tuple((1-t)*x+t*y for x,y in zip(a,b))

def mix_linear(left,right,weight):
    a,b,t=color(left),color(right),unit(weight)
    return tuple(encode_srgb((1-t)*decode_srgb(x)+t*decode_srgb(y)) for x,y in zip(a,b))

def png(path,rows):
    """Write a minimal lossless RGB PNG using only the standard library."""
    height=len(rows);width=len(rows[0])//3
    def chunk(kind,data):
        return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff)
    raw=b''.join(b'\x00'+row for row in rows)
    Path(path).write_bytes(b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw))+chunk(b'IEND',b''))

def export(output,left=(0,0,0),right=(1,1,1),weight=.5):
    left,right,t=color(left),color(right),unit(weight)  # validate before any writes
    rows=[]
    for n in range(257):
        w=n/256
        a=tuple(map(quantize8,mix_encoded(left,right,w)))
        b=tuple(map(quantize8,mix_linear(left,right,w)))
        rows.append([w,*a,*b])
    dest=Path(output);dest.mkdir(parents=True,exist_ok=True)
    with (dest/'ramp.csv').open('w',newline='') as f:
        writer=csv.writer(f);writer.writerow(['weight','encoded_r8','encoded_g8','encoded_b8','linear_r8','linear_g8','linear_b8']);writer.writerows(rows)
    image=[]
    for mode in [mix_encoded,mix_linear]:
        row=b''.join(bytes(map(quantize8,mode(left,right,n/256))) for n in range(257))
        image.extend([row]*48)
    png(dest/'patches.png',image)
    result={'kind':'constructed sRGB arithmetic','physical_measurement':False,'left':left,'right':right,'right_weight':t,'encoded_mix8':list(map(quantize8,mix_encoded(left,right,t))),'linear_light_mix8':list(map(quantize8,mix_linear(left,right,t))),'linear_half_encoded':encode_srgb(.5),'code128_light':decode_srgb(128/255),'code188_light':decode_srgb(188/255),'rows':len(rows),'scope':'normalized in-gamut channels; no perceptual or display calibration claim'}
    (dest/'result.json').write_text(json.dumps(result,indent=2)+'\n')
    return result

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output',required=True)
    parser.add_argument('--weight',type=float,default=.5)
    parser.add_argument('--left',default='0,0,0');parser.add_argument('--right',default='1,1,1')
    args=parser.parse_args()
    try:
        a=tuple(float(x) for x in args.left.split(','));b=tuple(float(x) for x in args.right.split(','))
        result=export(args.output,a,b,args.weight)
    except (ValueError,OverflowError) as exc: parser.error(str(exc))
    print(json.dumps(result,sort_keys=True))
if __name__=='__main__':main()
test_srgb_lab.py — complete file
import csv
import decimal
import json
import math
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import srgb_lab as s

class SRGBTests(unittest.TestCase):
    def test_linear_black_white_midpoint_quantizes188(self):
        self.assertEqual(s.quantize8(s.encode_srgb(0.5)),188)
    def test_encoded_midpoint_quantizes128(self):
        self.assertEqual(s.quantize8(0.5),128)
    def test_endpoints(self):
        for fn in [s.decode_srgb,s.encode_srgb]:
            self.assertEqual(fn(0),0)
            self.assertAlmostEqual(fn(1),1,places=14)
    def test_code128_light_value(self):
        self.assertAlmostEqual(s.decode_srgb(128/255),0.21586050011389926,places=14)
    def test_code188_is_quantized_not_exact_half(self):
        self.assertAlmostEqual(s.decode_srgb(188/255),0.5028864580325687,places=14)
        self.assertNotEqual(s.decode_srgb(188/255),0.5)
    def test_decode_branch_boundary(self):
        self.assertEqual(s.decode_srgb(0.04045),0.04045/12.92)
    def test_encode_branch_boundary(self):
        self.assertEqual(s.encode_srgb(0.0031308),12.92*0.0031308)
    def test_rounded_join_mismatch_is_bounded(self):
        a=s.encode_srgb(0.0031308)
        b=s.encode_srgb(math.nextafter(0.0031308,1.0))
        self.assertLess(abs(a-b),3e-8)
        self.assertGreater(a,b)  # Published rounded constants; not exact continuity.
    def test_high_precision_decimal_encoder(self):
        with decimal.localcontext() as ctx:
            ctx.prec=60
            D=decimal.Decimal
            for raw in ['0.01','0.18','0.25','0.5','0.75','0.99']:
                exact=D('1.055')*(D(raw)**(D(5)/D(12)))-D('0.055')
                self.assertLess(abs(s.encode_srgb(float(raw))-float(exact)),3e-15)
    def test_high_precision_decimal_decoder(self):
        with decimal.localcontext() as ctx:
            ctx.prec=60
            D=decimal.Decimal
            for raw in ['0.05','0.18','0.25','0.5','0.75','0.99']:
                exact=((D(raw)+D('0.055'))/D('1.055'))**(D(12)/D(5))
                self.assertLess(abs(s.decode_srgb(float(raw))-float(exact)),3e-15)
    def test_all256_codes_round_trip(self):
        for n in range(256):
            self.assertEqual(s.quantize8(s.encode_srgb(s.decode_srgb(n/255))),n)
    def test_ordered_eight_bit_decoder_and_grid_encoder(self):
        a=[s.decode_srgb(n/255) for n in range(256)]
        b=[s.encode_srgb(n/4096) for n in range(4097)]
        self.assertTrue(all(x<=y for x,y in zip(a,a[1:])))
        self.assertTrue(all(x<=y for x,y in zip(b,b[1:])))
    def test_round_trip_grid_has_declared_join_tolerance(self):
        for n in range(4097):
            x=n/4096
            self.assertLess(abs(s.decode_srgb(s.encode_srgb(x))-x),4e-8)
    def test_red_blue_mixes_have_different_codes(self):
        a=(1,0,0);b=(0,0,1)
        self.assertEqual(tuple(map(s.quantize8,s.mix_encoded(a,b,.5))),(128,0,128))
        self.assertEqual(tuple(map(s.quantize8,s.mix_linear(a,b,.5))),(188,0,188))
    def test_asymmetric_weight_is_linear_only_after_decode(self):
        a=(.2,.4,.8);b=(.9,.6,.1);t=.25
        y=s.mix_linear(a,b,t)
        for i in range(3):
            self.assertAlmostEqual(s.decode_srgb(y[i]),.75*s.decode_srgb(a[i])+.25*s.decode_srgb(b[i]),places=13)
    def test_weight_endpoints_and_same_color(self):
        a=(.1,.2,.3);b=(.8,.7,.6)
        for fn in [s.mix_linear,s.mix_encoded]:
            self.assertTrue(all(abs(x-y)<4e-8 for x,y in zip(fn(a,b,0),a)))
            self.assertTrue(all(abs(x-y)<4e-8 for x,y in zip(fn(a,b,1),b)))
            self.assertTrue(all(abs(x-y)<4e-8 for x,y in zip(fn(a,a,.37),a)))
    def test_swap_and_complement_weight(self):
        a=(.1,.2,.9);b=(.7,.8,.3)
        for fn in [s.mix_linear,s.mix_encoded]:
            self.assertTrue(all(abs(x-y)<1e-14 for x,y in zip(fn(a,b,.2),fn(b,a,.8))))
    def test_unit_input_refusal(self):
        for value in [True,False,None,'0.5',complex(1,0),float('nan'),float('inf'),-0.01,1.01,10**500]:
            for fn in [s.decode_srgb,s.encode_srgb,s.quantize8]:
                with self.assertRaises(ValueError):fn(value)
    def test_color_shape_refusal(self):
        for color in [None,'red',[],[0,1],[0,1,0,1],[0,True,1],[0,float('nan'),1]]:
            with self.assertRaises(ValueError):s.mix_linear(color,(0,0,0),.5)
    def test_weight_refusal(self):
        for t in [True,None,'0.5',-1,2,float('nan'),10**500]:
            with self.assertRaises(ValueError):s.mix_encoded((0,0,0),(1,1,1),t)
    def test_quantization_tie_rule(self):
        for n in [0,1,127,200,254]:
            self.assertEqual(s.quantize8((n+.5)/255),n+1)
    def test_cli_exports_constructed257_rows_and_png(self):
        with tempfile.TemporaryDirectory() as td:
            result=subprocess.run([sys.executable,str(Path(s.__file__)),'--output',td],capture_output=True,text=True)
            self.assertEqual(result.returncode,0,result.stderr)
            rows=list(csv.DictReader((Path(td)/'ramp.csv').open()))
            self.assertEqual(len(rows),257)
            self.assertEqual(rows[128]['encoded_r8'],'128')
            self.assertEqual(rows[128]['linear_r8'],'188')
            self.assertTrue((Path(td)/'patches.png').read_bytes().startswith(b'\x89PNG\r\n\x1a\n'))
            self.assertFalse(json.loads((Path(td)/'result.json').read_text())['physical_measurement'])
    def test_cli_rejects_bad_range_before_creating_output(self):
        with tempfile.TemporaryDirectory() as td:
            dest=Path(td)/'must-not-exist'
            result=subprocess.run([sys.executable,str(Path(s.__file__)),'--output',str(dest),'--weight','nan'],capture_output=True,text=True)
            self.assertNotEqual(result.returncode,0)
            self.assertFalse(dest.exists())

if __name__=='__main__':unittest.main()

Open the offline reader and reproduction instructions. The delivered reader ZIP contains this article, preview, original figures, code, tests and blank and constructed data. The blank worksheet is intentionally empty; generated outputs are explicitly constructed.