Image color processing C reference
These private services are declared in rbcImage.h and implemented in rbcImage.c. See Image color processing for
algorithms and current limitations.
-
void Rbc_ColorImageToGreyscale(Rbc_ColorImage image)
Replace RGB channels in place with their weighted greyscale value.
Borrow image and retain its dimensions, storage and alpha values. Apply coefficients 0.212671, 0.715160 and 0.072169 to stored RGB bytes, clamp and truncate to a byte. No gamma conversion or temporary image is involved.
- Parameters:
image – [inout] Borrowed writable image; RGB is replaced and alpha retained.
-
Rbc_ColorImage Rbc_ConvolveColorImage(Rbc_ColorImage src, Filter2D *filterPtr)
Return a newly owned, same-size image filtered over RGB with opaque alpha.
Borrow source and filter. The effective radius is max(1, (int)support). The caller supplies a row-major square kernel of (2 * radius + 1)^2 finite coefficients and a finite nonzero divisor in sum. scale is unused. Samples beyond the image repeat its edge pixels. The kernel is traversed as stored, without reversal. Release the result with Rbc_FreeColorImage(). Invalid filter metadata panics; kernel length and coefficients are not validated.
- Parameters:
src – [in] Borrowed valid source image; ownership remains with the caller.
filterPtr – [in] Borrowed square kernel descriptor; finite coefficients and nonzero sum are required.
-
int Rbc_QuantizeColorImage(Rbc_ColorImage src, Rbc_ColorImage dest, int reduceColors)
Map source RGB into an existing, equal-size destination while preserving alpha.
Borrow both images; identical source and destination are supported. Require 1..256 requested colors and matching dimensions, otherwise return TCL_ERROR without a Tcl diagnostic or pixel changes. Empty images return TCL_OK. Temporary histogram, boxes and lookup table are released internally.
Mapping uses the same one-based channel bins as histogram construction and lookup-table population. Some split diagnostics use stderr.
- Parameters:
src – [in] Borrowed valid source image; ownership remains with the caller.
dest – [inout] Borrowed writable destination image with the required matching dimensions.
reduceColors – [in] Requested palette size in [1,256].
Palette-reduction implementation
These structures and helpers implement the cumulative-moment partitioner in rbcImage.c. See Image color processing for
the stage ordering and invariants.
- group RGB quantization internals
Functions
-
static ColorImageStatistics *GetColorImageStatistics(Rbc_ColorImage image)
Build an owned five-bit RGB histogram from a borrowed image.
Allocates zeroed 33-cubed arrays of signed 64-bit moments. For each pixel, bins each channel as (value >> 3) + 1 and accumulates count, original eight-bit channel values and their squared sum. Index-zero planes stay zero for cumulative queries. Alpha does not affect inclusion or weight. Returns an allocation freed with ckfree; does not modify the source.
- Parameters:
image – [in] Borrowed valid RGBA image; mutation policy is specified above.
-
static void M3d(ColorImageStatistics *s)
Convert raw color histograms into three-dimensional prefix sums.
Mutates all five arrays in the borrowed statistics record. Requires the raw histogram and zero boundary planes produced by GetColorImageStatistics. Uses stack row/area accumulators, with no new owned allocation. This is a one-time transformation, not an idempotent query. Subsequent box helpers require the cumulative representation, not raw bins.
- Parameters:
s – [inout] Writable raw histogram, converted once into cumulative moments.
-
static Moment Volume(Cube *cubePtr, Moment m[33][33][33])
Query a cumulative statistic over one half-open RGB box.
Borrows the cube and prefix-sum array. Bounds are lower-exclusive and upper-inclusive, within 0..32. Returns the eight-corner inclusion-exclusion sum without modifying either argument. Requires valid ordered bounds; performs no bounds checks or allocation.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
m – [in] Borrowed 33 by 33 by 33 cumulative moment array.
-
static Moment Bottom(Cube *cubePtr, unsigned char dir, Moment m[33][33][33])
Compute the cut-independent part of a lower subbox sum.
Borrows the cube and cumulative array. RED, GREEN or BLUE selects the coordinate whose upper bound will be replaced. Add Top at a candidate position to obtain the lower subbox volume. Unknown directions return zero; callers must still supply valid bounds and a supported direction.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
dir – [in] Color axis selector: RED, GREEN or BLUE.
m – [in] Borrowed 33 by 33 by 33 cumulative moment array.
-
static Moment Top(Cube *cubePtr, unsigned char dir, int pos, Moment m[33][33][33])
Compute the cut-dependent part of a lower subbox sum.
Borrows the cube and cumulative array. Replaces the selected upper bound with pos; Bottom plus this result is the proposed lower subbox volume. Requires pos in the valid grid range and a RED, GREEN or BLUE direction. Unknown directions return zero; no bounds checking or mutation occurs.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
dir – [in] Color axis selector: RED, GREEN or BLUE.
pos – [in] Candidate upper bound along dir, within the valid moment grid.
m – [in] Borrowed 33 by 33 by 33 cumulative moment array.
-
static double Variance(Cube *cubePtr, ColorImageStatistics *s)
Return the population-weighted squared RGB error of a box.
Uses cumulative sums from a borrowed statistics record and cube. Returns zero for nonpositive population, otherwise the squared-color sum minus the sum of squared channel totals divided by population. Converts totals to double before squaring. This is variance times population, not mean variance; floating-point cancellation is not explicitly clamped.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
s – [in] Borrowed cumulative color statistics; not a raw histogram.
-
static double Maximize(Cube *cubePtr, unsigned char dir, int first, int last, int *cut, Moment rWhole, Moment gWhole, Moment bWhole, Moment wWhole, ColorImageStatistics *s)
Choose a nonempty split maximizing the two mean-color scores.
Borrows the cube, cumulative statistics and whole-box channel/count sums. Examines candidate cuts in [first, last) along dir, skipping a cut when either population is zero. Writes -1 initially to cut, replacing it only on a strictly greater score; ties retain the earliest winning position. Returns the best score, or zero if none exceeds zero. Does not mutate boxes or statistics. Inputs must describe the same valid whole box.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
dir – [in] Color axis selector: RED, GREEN or BLUE.
first – [in] Inclusive first candidate cut position.
last – [in] Exclusive final candidate cut position.
cut – [out] Required output initialized to -1, then set to the best winning cut.
rWhole – [in] Red-channel sum for the whole box.
gWhole – [in] Green-channel sum for the whole box.
bWhole – [in] Blue-channel sum for the whole box.
wWhole – [in] Population of the whole box.
s – [in] Borrowed cumulative color statistics; not a raw histogram.
-
static int Cut(Cube *set1, Cube *set2, ColorImageStatistics *s)
Split one populated color box along the best RGB direction.
Borrows cumulative statistics; set1 and set2 must be distinct writable cube records. Evaluates candidate cuts on all axes. Ties favor red, then green, then blue. Returns zero without modifying cubes when no red cut is available in the winning red case. On success, narrows set1 to the lower box, writes set2 as the upper box, recomputes geometric volumes and returns one. Does not allocate or update the statistical arrays.
- Parameters:
set1 – [inout] Writable original box, narrowed to the lower partition on success.
set2 – [out] Distinct writable output box receiving the upper partition on success.
s – [in] Borrowed cumulative color statistics; not a raw histogram.
-
static int SplitColorSpace(ColorImageStatistics *s, Cube *cubes, int nColors)
Greedily partition RGB space into at most nColors boxes.
Requires nColors at least one and a writable cube array with that capacity; statistics must already contain prefix sums. Starts with the full 0..32 box, repeatedly splits the selected box and selects the largest remaining positive variance. Failed cuts disable that box and retry the slot. One-cell boxes are assigned zero variance; selection ties favor the first box. Returns the number of initialized boxes, possibly below nColors. Owns and frees a temporary variance array. Emits no early-stop message.
- Parameters:
s – [in] Borrowed cumulative color statistics; not a raw histogram.
cubes – [out] Writable array with capacity for nColors boxes.
nColors – [in] Positive number of partition boxes requested or supplied, as described above.
-
static void Mark(Cube *cubePtr, int label, unsigned int tag[33][33][33])
Fill the lookup-table cells covered by one color box.
Borrows a valid cube and writable 33-cubed tag table. Writes label to lower-exclusive, upper-inclusive cells on each axis; boundary index zero is untouched for ordinary boxes. Does not allocate or inspect image data. The integer label carries a packed pixel value supplied by the caller.
- Parameters:
cubePtr – [in] Borrowed box with valid lower-exclusive and upper-inclusive RGB bounds.
label – [in] Packed representative pixel value to store in the selected cells.
tag – [inout] Writable 33 by 33 by 33 lookup table.
-
static unsigned int *CreateColorLookupTable(ColorImageStatistics *s, Cube *cubes, int nColors)
Allocate packed representative RGB values for the partition boxes.
Borrows cumulative statistics and nColors initialized cubes. Returns an owned zeroed 33-cubed unsigned-int table, freed with ckfree. Computes integer channel means, scales by 257 then shifts by eight, and marks each cube with an opaque Pix32 value. Empty boxes print a stderr diagnostic and use black; ordinary nonempty splits avoid that path. The mapping pass restores source alpha separately. Does not change source statistics.
- Parameters:
s – [in] Borrowed cumulative color statistics; not a raw histogram.
cubes – [in] Borrowed array of nColors initialized partition boxes.
nColors – [in] Positive number of partition boxes requested or supplied, as described above.
-
static void MapColors(Rbc_ColorImage src, Rbc_ColorImage dest, unsigned int lut[33][33][33])
Replace RGB using one-based histogram bins while retaining source alpha.
Borrows a source image, matching destination storage and packed lookup table. Visits the source pixel count without checking destination shape. Saves each alpha byte before writing, so exact source/destination aliasing is supported. Uses (channel >> 3) + 1 for every table coordinate. Does not allocate, dither or search for the nearest representative color.
- Parameters:
src – [in] Borrowed valid source image; ownership remains with the caller.
dest – [inout] Borrowed writable destination image with the required matching dimensions.
lut – [in] Borrowed 33 by 33 by 33 packed-pixel lookup table.
-
struct Cube
Lower-exclusive, upper-inclusive box in the five-bit RGB grid.
Bounds lie in 0..32. vol is geometric cell count, not pixel population; Cut updates it for the two resulting boxes. The owner allocates the array.
Public Members
-
int r0
min, max values: min exclusive max inclusive
-
int r1
min, max values: min exclusive max inclusive
-
int g0
Lower green boundary, excluded from the box sum.
-
int g1
Upper green boundary, included in the box sum.
-
int b0
Lower blue boundary, excluded from the box sum.
-
int b1
Upper blue boundary, included in the box sum.
-
int vol
Box volume in histogram cells.
-
int r0
-
struct ColorImageStatistics
Owned raw RGB histograms, transformed in place into cumulative moments.
Arrays use bins 1..32 with zero boundary planes. gm2 stores squared-color sums, not a precomputed variance. Alpha is absent. GetColorImageStatistics allocates the record; M3d changes its representation; the owner frees it.
-
static ColorImageStatistics *GetColorImageStatistics(Rbc_ColorImage image)
Data records and member contracts
These records describe stored state and resource ownership. Their presence in the reference does not make private layouts part of the installed C API.
-
struct TrueColorMasks
Display-specific bit shifts for packing RGB channels into native pixels.
Public Members
-
int redAdjust
Bit adjustment for the red component.
-
int greenAdjust
Bit adjustment for the green component.
-
int blueAdjust
Bit adjustment for the blue component.
-
int redMaskShift
Native pixel mask shift for the red component.
-
int greenMaskShift
Native pixel mask shift for the green component.
-
int blueMaskShift
Native pixel mask shift for the blue component.
-
int redAdjust