Module

Puregrain

Package
purescript-puregrain
Repository
roman-mkh/puregrain

Error-diffusion and ordered dithering, in one import. This module re-exports what a typical application needs:

  • ditherImage, which dithers an image in memory; ditherRows, which dithers a lazy stream of rows, each when it's needed; and initDithering with ditherRow, one row at a time from any source;
  • the kernels floydSteinberg, atkinson, jarvisJudiceNinke, stucki, burkes, sierra3, sierra2, sierraLite, fan, shiauFan and shiauFan2, and noDiffusion for none;
  • the quantizers threshold, nearestLevel with evenRamp, and perChannel for color; nearestColor with the palette presets; bayer and ordered for ordered dithering;
  • ditherImageBy, ditherRowsBy and initDitheringBy, the same with their settings in a DitherParams, built from defaults with withKernel, withGamma and withScan (raster, the default, or serpentine, the rows alternating), and withDiffusion for a Diffusion: fixedKernel with a kernel, or ostromoukhov and zhouFang, whose weights depend on the pixel's tone;
  • ditherImageWith, ditherRowsWith and initDitheringWith, the same with a gamma curve, gammaOff, gamma1p2, gamma1p5, gamma1p8 or gammaSrgb, which says how the stored numbers turn into light; and toGray, a color's gray by that curve;
  • the pixel types RGB and RGBA, and the types for signatures.

Import it qualified, as names like threshold or c64 are short:

import Puregrain as P

dithered = P.ditherImage P.floydSteinberg (P.threshold 128.0) image

The building blocks for your own variants (distance metrics, threshold maps, custom quantizers) are in the modules they come from: Puregrain.Palette, Puregrain.Ordered, Puregrain.Quantize, Puregrain.Pixel, Puregrain.Kernel and Puregrain.Gamma. Dithering with cells, as on the screens of 8-bit machines, is in Puregrain.Cells and Puregrain.Machine.ZxSpectrum, outside this module.

Re-exports from Puregrain.Dither

#Scan Source

data Scan

The order the pixels are visited in, for withScan: raster or serpentine. Opaque.

#Dithering Source

newtype Dithering a

An image being dithered one row at a time, for ditherRow: the settings, the quantizer, and the error waiting for the rows still to come; a is the pixel type. Opaque.

An immutable value: keep and reuse one, for an undo, say. Dithering a row from it again redoes that row's work, and no more.

#DitherParams Source

newtype DitherParams

How an image is dithered, apart from the quantizer: the diffusion, where each pixel's error goes (a kernel, or a method by tone); the gamma, in which light; and the scan, the order the pixels are visited in. Opaque: start from defaults and change one setting at a time with the with… functions, chained with #:

params = defaults # withKernel floydSteinberg # withGamma gammaSrgb # withScan serpentine

dithered = ditherImageBy params (threshold 128.0) image

The order of the with… calls doesn't matter; a later call of the same one replaces the earlier setting. The quantizer is an argument of its own, since its type depends on the driver: a Quantize a for ditherImageBy, a cell rule for Puregrain.Cells.ditherCellsBy.

#Diffusion Source

data Diffusion

How each pixel's error is spread, for withDiffusion: a kernel's fixed weights (fixedKernel), or weights that depend on the pixel's tone (ostromoukhov). Opaque.

#zhouFang Source

zhouFang :: Diffusion

Zhou and Fang's error diffusion with threshold modulation (SIGGRAPH 2003): Ostromoukhov's three neighbours with weights of its own by tone, and a threshold raised at random, 128 + (noise mod 128) × m(tone), with a strength m by tone. The noise breaks up the regular patterns Ostromoukhov's method still shows in the mid-tones, for a little more grain.

The threshold is raised by a fraction of the interval between the two levels around a value, so with more levels each interval gets the black-and-white patterns, scaled; per channel by each channel's tone; in a machine's cells along the cell's two colors. Palettes, ordered dithering and quantizers of one's own have no threshold to raise: with them, it diffuses with its weights alone. The noise comes from a hash of the pixel's position, with a fixed seed: the same picture dithers alike everywhere, every time. It always scans serpentine. Its tables, its sources and what it looks like: docs/weights-by-tone/zhou-fang.md.

#withScan Source

withScan :: Scan -> DitherParams -> DitherParams

Sets the scan, the order the pixels are visited in.

  • Scan: raster, every row left to right (the default), or serpentine, the rows alternating.
  • DitherParams: the settings to change.

Returns the settings with that scan, the others unchanged.

#withKernel Source

withKernel :: Kernel -> DitherParams -> DitherParams

Sets the kernel: the same as withDiffusion (fixedKernel kernel).

  • Kernel: where each pixel's error goes, from Puregrain.Kernel; noDiffusion for nowhere.
  • DitherParams: the settings to change.

Returns the settings with that kernel, the others unchanged.

#withGamma Source

withGamma :: Gamma -> DitherParams -> DitherParams

Sets the gamma.

  • Gamma: how the stored numbers turn into light, from Puregrain.Gamma: gammaOff, gamma1p2, gamma1p5, gamma1p8 or gammaSrgb. Which for which view: docs/gamma.md.
  • DitherParams: the settings to change.

Returns the settings with that gamma, the others unchanged.

#withDiffusion Source

withDiffusion :: Diffusion -> DitherParams -> DitherParams

Sets the diffusion. It and withKernel set the same setting, so the later of the two counts.

  • Diffusion: fixedKernel with a kernel, or ostromoukhov.
  • DitherParams: the settings to change.

Returns the settings with that diffusion, the others unchanged.

params = defaults # withDiffusion ostromoukhov

#serpentine Source

serpentine :: Scan

Serpentine scanning: the rows alternate, the first (row 0) left to right, the second right to left, and so on, top to bottom. On a row scanned right to left the kernel is mirrored, so each pixel's error still goes to pixels not yet processed: an offset's dx then counts to the left. It's the usual remedy for the patterns error diffusion draws when every row is scanned the same way.

Each pixel's quantizer still gets its own position, counted from the image's left and top edges, so ordered dithering and machine cells work as with raster. With noDiffusion it changes nothing. What it changes, and what it doesn't: docs/error-diffusion.md.

#raster Source

raster :: Scan

Every row left to right, top to bottom: the default.

#ostromoukhov Source

ostromoukhov :: Diffusion

Ostromoukhov's variable-coefficient error diffusion (SIGGRAPH 2001): three neighbours, right, down-left and down, whose weights depend on the pixel's tone, from a table tuned so that flat areas of every gray come out as even patterns, without the lines and lattices of Floyd–Steinberg in its worst grays.

Each channel looks its weights up by its own tone. The tone is where the pixel's original value lies between the two levels around it, so that a mix of two levels gets the row tuned for that mix: with black and white, the value itself; with a palette, the mean of the pixel's channels, the same in each, as palette colors have no order to lie between and the palette decides on the whole pixel; in a machine's cells, the share along the cell's two colors.

It always scans serpentine, as the method is defined, whatever withScan says. Its table, its sources and what it looks like: docs/weights-by-tone/ostromoukhov.md.

#initDitheringWith Source

initDitheringWith :: forall a. Ring a => Scalable a => ColorChannels a => Gamma -> Kernel -> Quantize a -> Dithering a

The state before the first row, for ditherRow, with a gamma and a kernel.

  • a and Gamma: as for ditherImageWith.
  • Kernel and Quantize a: as for initDithering.

Returns what initDitheringBy (defaults # withKernel kernel # withGamma gamma) returns.

#initDitheringBy Source

initDitheringBy :: forall a. Ring a => Scalable a => MapChannels a => ColorChannels a => DitherParams -> Quantize a -> Dithering a

The state before the first row, for ditherRow, with the settings given.

  • a, DitherParams and Quantize a: as for ditherImageBy.

Dithers nothing yet; the first row fixes the image's width. ditherRow then gives the same rows as ditherImageBy, each as stored values.

#initDithering Source

initDithering :: forall a. Ring a => Scalable a => Kernel -> Quantize a -> Dithering a

The state before the first row, for ditherRow, with a kernel and no other setting.

  • a, Kernel and Quantize a: as for ditherImage.

Returns what initDitheringBy (defaults # withKernel kernel) returns.

#fixedKernel Source

fixedKernel :: Kernel -> Diffusion

A kernel's diffusion: the same weights for every pixel, from Puregrain.Kernel.

#ditherRowsWith Source

ditherRowsWith :: forall a. Ring a => Scalable a => ColorChannels a => Gamma -> Kernel -> Quantize a -> List (Array a) -> List (Array a)

Dithers a lazy stream of rows, with a gamma and a kernel.

  • a and Gamma: as for ditherImageWith.
  • Kernel, Quantize a, LL.List (Array a): as for ditherRows.

Returns what ditherRowsBy (defaults # withKernel kernel # withGamma gamma) returns.

#ditherRowsBy Source

ditherRowsBy :: forall a. Ring a => Scalable a => MapChannels a => ColorChannels a => DitherParams -> Quantize a -> List (Array a) -> List (Array a)

Dithers a lazy stream of rows, with the settings given.

  • a, DitherParams and Quantize a: as for ditherImageBy.
  • LL.List (Array a): the rows, top to bottom, all of the same length; the list may be endless.

Returns the dithered rows as a lazy list, the same rows as ditherImageBy. Each row is read and dithered only when its result is first needed, so only the rows in flight are in memory. At a row whose length differs from the first row's, it stops with an error naming the row; the rows before it have come out.

#ditherRows Source

ditherRows :: forall a. Ring a => Scalable a => Kernel -> Quantize a -> List (Array a) -> List (Array a)

Dithers a lazy stream of rows, with a kernel and no other setting.

  • a, Kernel and Quantize a: as for ditherImage.
  • LL.List (Array a): the rows, as for ditherRowsBy.

Returns what ditherRowsBy (defaults # withKernel kernel) returns.

#ditherRow Source

ditherRow :: forall a. Ring a => Scalable a => Dithering a -> Array a -> Either String { next :: Dithering a, row :: Array a }

Dithers the next row.

  • Dithering a: the state, from initDitheringBy, initDithering, initDitheringWith or the previous row.
  • Array a: the row, as long as the first one.

Returns the dithered row and the state for the next one: the same rows as the matching ditherImage…. Left, with a message naming the row, for a row of a different length; the state passed in is untouched, so you can carry on with a corrected row.

#ditherImageWith Source

ditherImageWith :: forall a. Ring a => Scalable a => ColorChannels a => Gamma -> Kernel -> Quantize a -> Array (Array a) -> Array (Array a)

Dithers an image in memory, with a gamma and a kernel.

  • a: the pixel type, as for ditherImageBy but without MapChannels: any type with Ring, Scalable and ColorChannels.
  • Gamma: how the stored numbers turn into light: gammaOff, the same as ditherImage, or gamma1p2, gamma1p5, gamma1p8 or gammaSrgb (linear light).
  • Kernel, Quantize a, Array (Array a): as for ditherImage.

Returns what ditherImageBy (defaults # withKernel kernel # withGamma gamma) returns.

ditherImageWith gammaSrgb floydSteinberg (threshold 128.0) image

#ditherImageBy Source

ditherImageBy :: forall a. Ring a => Scalable a => MapChannels a => ColorChannels a => DitherParams -> Quantize a -> Array (Array a) -> Array (Array a)

Dithers an image in memory, with the settings given.

  • a: the pixel type, Number for gray, RGB or RGBA; any type with Ring, Scalable, MapChannels and ColorChannels works.
  • DitherParams: the kernel, the gamma and the scan, from defaults and the with… functions.
  • Quantize a: picks each pixel's output value.
  • Array (Array a): the image, rows top to bottom, each left to right, all of the same length.

Returns the dithered image, all at once, as stored values. Under a gamma other than gammaOff, each row is taken to light, dithered there, and brought back: the error and the amounts of light (ordered dithering's patterns) are in light; the choices of the nearest level or color stay on stored values, as the eye sees them; a level or a palette color of whole numbers comes back exactly. Stops with an error naming a row whose length differs from the first row's.

ditherImageBy (defaults # withKernel floydSteinberg # withGamma gammaSrgb) (threshold 128.0) image

#ditherImage Source

ditherImage :: forall a. Ring a => Scalable a => Kernel -> Quantize a -> Array (Array a) -> Array (Array a)

Dithers an image in memory, with a kernel and no other setting.

  • a: the pixel type, Number for gray, RGB or RGBA; any type with Ring and Scalable works, ColorChannels not needed.
  • Kernel: where each pixel's error goes; noDiffusion for nowhere.
  • Quantize a: picks each pixel's output value.
  • Array (Array a): the image, as for ditherImageBy.

Returns what ditherImageBy (defaults # withKernel kernel) returns.

#defaults Source

defaults :: DitherParams

The settings to start from, each one neutral: no diffusion (noDiffusion), so each pixel is only quantized; gammaOff; and raster, every row left to right. Dithering with them alone is plain quantizing, or pure ordered dithering with a quantizer from Puregrain.Ordered; add a kernel with withKernel for error diffusion.

Re-exports from Puregrain.Gamma

#Gamma Source

data Gamma

A curve between a picture's stored values and light: one of Puregrain.Gamma's presets, gammaOff, gamma1p2, gamma1p5, gamma1p8 and gammaSrgb.

#toGray Source

toGray :: Gamma -> RGB -> Number

A color's gray, for dithering a color picture in gray.

  • Gamma: the curve, which decides the formula; give the dithering the same one.
  • RGB: the color, as stored.

Returns the gray as a stored value, 0 to 255. A neutral color, with red, green and blue equal, gives exactly that value. With gammaOff, the gray is luma, 0.299 R + 0.587 G + 0.114 B on the stored values, the classic conversion. With a curve, it's the gray that gives off as much light as the color: 0.2126 R + 0.7152 G + 0.0722 B on the channels' light (luminance, with gammaSrgb), brought back to a stored value. Saturated colors then come out lighter than with luma, pure blue 76 instead of 29 with gammaSrgb; natural colors such as skin barely change.

toGray gammaOff (RGB { r: 0.0, g: 0.0, b: 255.0 })    -- 29.07
toGray gammaSrgb (RGB { r: 0.0, g: 0.0, b: 255.0 })   -- 75.96…

ditherImageWith gammaSrgb floydSteinberg (threshold 128.0)
  (map (map (toGray gammaSrgb)) image)

#gammaSrgb Source

gammaSrgb :: Gamma

Linear light: the sRGB standard's curve (IEC 61966-2-1), a straight piece near black and a power of 2.4 above it, which behaves much like a power of 2.2 overall.

#gammaOff Source

gammaOff :: Gamma

No conversion: the stored numbers are taken as amounts of light, as dithering has always taken them. The default.

#gamma1p8 Source

gamma1p8 :: Gamma

A power curve: light = (value / 255)^1.8 × 255, the gamma of Apple RGB, the classic Macintosh's color space.

#gamma1p5 Source

gamma1p5 :: Gamma

A power curve: light = (value / 255)^1.5 × 255.

#gamma1p2 Source

gamma1p2 :: Gamma

A power curve: light = (value / 255)^1.2 × 255.

Re-exports from Puregrain.Kernel

#Offset Source

type Offset = { dx :: Int, dy :: Int, weight :: Number }

One neighbour that gets a share of a pixel's error.

  • dx: columns to the right; negative to the left. With serpentine scanning (Puregrain.Dither.serpentine), a row scanned right to left mirrors the kernel: dx then counts to the left.
  • dy: rows down.
  • weight: the share of the error.

#Kernel Source

newtype Kernel

A checked list of neighbours. Build one with fromOffsets, or use a ready-made one. Opaque, so every kernel ditherImage gets is valid.

Instances

#stucki Source

stucki :: Kernel

Stucki (Peter Stucki, IBM Zurich, 1981): 12 neighbours over the next 2 rows, like Jarvis–Judice–Ninke, with weights that give a clean, sharp result.

#sierraLite Source

sierraLite :: Kernel

Sierra Lite (Frankie Sierra, 1989–1990; also "Filter Lite" or "Sierra-2-4A"): 3 neighbours, one fewer than Floyd–Steinberg, for similar results.

#sierra3 Source

sierra3 :: Kernel

Sierra 3 (Frankie Sierra, 1989–1990; also "Sierra" or "three-row Sierra"): 10 neighbours over the next 2 rows, for results like Jarvis–Judice–Ninke's with fewer neighbours.

#sierra2 Source

sierra2 :: Kernel

Sierra 2 (Frankie Sierra, 1989–1990; also "two-row Sierra"): 7 neighbours over the next row, a faster Sierra 3.

#shiauFan2 Source

shiauFan2 :: Kernel

Shiau–Fan 2 (Jeng-Nan Shiau and Zhigang Fan, 1993): the same aim with 5 neighbours, reaching three columns to the left.

#shiauFan Source

shiauFan :: Kernel

Shiau–Fan (Jeng-Nan Shiau and Zhigang Fan, 1993): 4 neighbours, with weights in eighths, made to reduce the "worm" patterns of Floyd–Steinberg.

#noDiffusion Source

noDiffusion :: Kernel

No neighbours: no error is passed on, so each pixel is quantized on its own. With Puregrain.Ordered, that's pure ordered dithering; with threshold or nearestLevel, plain rounding to a level.

#jarvisJudiceNinke Source

jarvisJudiceNinke :: Kernel

Jarvis–Judice–Ninke (1976): 12 neighbours over the next 2 rows, for the smoothest texture, at about 2.5 times Floyd–Steinberg's cost.

#floydSteinberg Source

floydSteinberg :: Kernel

Floyd–Steinberg (1976): 4 neighbours, the classic.

#fan Source

fan :: Kernel

Fan (Zhigang Fan, 1993): Floyd–Steinberg's 4 neighbours with one weight moved, its 1/16 from below-right to two columns left.

#burkes Source

burkes :: Kernel

Burkes (Daniel Burkes, 1988): Stucki without its last row, so 7 neighbours over the next row: a little less clean, at a lower cost.

#atkinson Source

atkinson :: Kernel

Atkinson (Apple, 1980s): 6 neighbours over the next 2 rows, each getting 1/8, so only 3/4 of the error is passed on: crisper and higher in contrast, at the cost of detail in dark and light tones.

Re-exports from Puregrain.Ordered

#ThresholdMap Source

newtype ThresholdMap

A threshold map: a grid of thresholds, each strictly between 0 and 1, repeated across the image. Build one with bayer or compileThresholdMap; opaque, so every map is checked: rectangular and non-empty.

#ordered Source

ordered :: ThresholdMap -> NonEmptyArray Number -> Quantize Number

Ordered dithering over levels. For a value v between two neighbouring levels lo < hi, it picks hi exactly when (v − lo) / (hi − lo) is above the pixel's threshold, else lo.

  • ThresholdMap: the thresholds, from bayer or compileThresholdMap.
  • NonEmptyArray Number: the levels, in any order; with 0 and 255, classic 1-bit ordered dithering. Levels that aren't whole numbers are rounded first, as Puregrain.Quantize.nearestLevel rounds them.

A value at a level stays that level; values beyond the lowest or highest level snap to it, as accumulated error can push them there in the hybrid with error diffusion. For color, lift it with perChannel, which gives every channel the same position.

With a gamma (Puregrain.Dither.ditherImageWith), v, lo and hi are amounts of light, so each pattern gives off the light it stands for. With few patterns, such as bayer 2 over two levels, the darkest grays then turn black: they're nearer to black's light than to the first pattern's.

#bayer Source

bayer :: Int -> Maybe ThresholdMap

The Bayer threshold map.

  • Int: the side, a power of 2 (1, 2, 4, 8, …).

Nothing for any other side. The thresholds are (rank + 0.5) / n² for side n (see compileThresholdMap). bayer 1 is 0.5 everywhere: ordered with it picks the nearer level, like nearestLevel.

-- pure 1-bit ordered dithering with the 8 × 8 map
map (\m -> ditherImage noDiffusion (ordered m (evenRamp 2)) image) (bayer 8)

Re-exports from Puregrain.Palette

#nearestColor Source

nearestColor :: NonEmptyArray RGB -> Quantize RGB

A quantizer that turns each pixel into the nearest palette color, all three channels together, by distance2; on a tie, the earlier color.

  • NonEmptyArray RGB: the palette, e.g. from Puregrain.Palette.Presets.
ditherImage floydSteinberg (nearestColor websafe216) image

With a gamma (Puregrain.Dither.ditherImageWith), the nearest color is still chosen on stored values, as the eye sees them: each corrected pixel is brought back from light for the comparison, and the chosen color taken to light, while the error stays in light. A pixel that's exactly a byte's light comes back as that byte, so without diffusion the result is the one ditherImage gives.

Its tone, for the methods whose weights depend on it (Puregrain.Dither.ostromoukhov), is the mean of the pixel's three channels, the same in every channel: one set of weights for the whole pixel, as the palette decides on the whole pixel.

Re-exports from Puregrain.Palette.Presets

#zxSpectrum Source

zxSpectrum :: NonEmptyArray RGB

The ZX Spectrum's 15 distinct colors: its 8 (black, blue, red, magenta, green, cyan, yellow, white) at normal brightness, then the 7 non-black ones with BRIGHT (bright black is black). Normal is 0xD8 = 216, about 85% of bright, the common model: the real colors were never measured, and many emulators use 0xD7 or 0xCD instead. This is the per-pixel palette; for the real machine's 2 colors per 8×8 cell, see Puregrain.Machine.ZxSpectrum. Source: en.wikipedia.org/wiki/ZX_Spectrum_graphic_modes; values as lospec.com/palette-list/zx-spectrum.

#websafe216 Source

websafe216 :: NonEmptyArray RGB

The 216 "web-safe" colors: every combination of 0, 51, 102, 153, 204 and 255 per channel (a 6×6×6 cube), r varying slowest, so it starts at black and ends at white. Being a complete grid, its nearest color is the nearest step in each channel separately — the same result as perChannel (nearestLevel (evenRamp 6)).

#cga16 Source

cga16 :: NonEmptyArray RGB

The 16-color IBM PC palette, CGA's "RGBI" colors in index order 0–15: each channel 0x00 or 0xAA, plus an intensity bit adding 0x55, with the IBM 5153 monitor's brown (color 6 is #AA5500, not dark yellow). Also EGA's and VGA's defaults and the DOS text colors; the Linux console uses the same values, in ANSI order. EGA's full 64 colors need no preset: perChannel (nearestLevel (evenRamp 4)). Source: en.wikipedia.org/wiki/Color_Graphics_Adapter (RGBI palette).

#c64 Source

c64 :: NonEmptyArray RGB

The Commodore 64's 16 colors, in VIC-II index order: black, white, red, cyan, purple, green, blue, yellow, orange, brown, light red, dark grey, grey, light green, light blue, light grey. There's no official RGB definition; these are Colodore's values, Pepto's model of the VIC-II's colors (2017), with the display set to brightness 47.5, contrast 100 and saturation 70. Source: pepto.de/projects/colorvic (the model); the values as in VICE's data/C64/colodore.vpl, which those settings reproduce exactly.

#blackWhite Source

blackWhite :: NonEmptyArray RGB

Black, then white. With nearestColor it dithers a color image straight down to pure black and white, choosing by RGB distance — which isn't brightness: pure green is nearer to black.

#ansi256 Source

ansi256 :: NonEmptyArray RGB

xterm's 256 colors: ansi16 (indices 0–15), a 6×6×6 cube (16–231, index 16 + 36r + 6g + b, levels 0, 95, 135, 175, 215, 255), and 24 grays (232–255, 8 + 10i). 7 cube colors repeat ansi16 ones, so 249 are distinct; nearestColor picks the earlier index of a pair. In a real terminal the first 16 come from its theme. Source: xterm's 256colres.pl.

#ansi16 Source

ansi16 :: NonEmptyArray RGB

The 16 ANSI terminal colors as xterm's defaults, in index order: black, red, green, yellow, blue, magenta, cyan, white, then the 8 bright ones. ANSI names the colors but defines no RGB, and terminals differ; the Linux console's values are cga16, in CGA order. Source: xterm's XTerm-col.ad, matching the xterm column of en.wikipedia.org/wiki/ANSI_escape_code.

Re-exports from Puregrain.Pixel

#RGBA Source

newtype RGBA

A color pixel with alpha: as RGB, plus a, which error diffusion treats like the other channels.

Constructors

Instances

#RGB Source

newtype RGB

A color pixel: red, green and blue, each from 0 to 255 by convention. Adds, subtracts and scales channel by channel, as error diffusion needs.

Constructors

Instances

#Gray Source

type Gray = Number

A gray pixel: one channel, a plain Number, from 0 (black) to 255 (white) by convention.

#ColorChannels Source

class ColorChannels a 

A pixel type whose color channels can be mapped one by one, leaving any other channel as it is: what converting a pixel between stored values and light needs (Puregrain.Gamma.toLight and fromLight), since alpha isn't on a light curve. Laws, as for MapChannels:

mapColorChannels identity == identity
mapColorChannels (f <<< g) == mapColorChannels f <<< mapColorChannels g

Instances

#MapChannels Source

class MapChannels a 

A pixel type whose channels can be mapped one by one: what Puregrain.Quantize.perChannel needs to run a one-channel quantizer on every channel, and what weights by tone (Puregrain.Dither.ostromoukhov) need to look each channel's weight up by its own tone. Laws, as for any functor-like mapping, and for zipChannels channel by channel:

mapChannels identity == identity
mapChannels (f <<< g) == mapChannels f <<< mapChannels g
zipChannels (\x _ -> x) p q == p
zipChannels (\_ y -> y) p q == q
mapChannels f (zipChannels g p q) == zipChannels (\x y -> f (g x y)) p q

Instances

#Scalable Source

class (Ring a) <= Scalable a 

A pixel type that error diffusion can scale by a kernel's weights. With Ring, for adding and subtracting error, it's what ditherImage needs from a pixel type.

Instances

Re-exports from Puregrain.Quantize

#Quantize Source

newtype Quantize a

A quantizer: picks a pixel's output value; a is the pixel type. Build one with quantize, or quantizeWith when the decision depends on the pixel's position; run one with runQuantize. Opaque, so its representation can change without breaking anyone.

It gets the pixel's corrected value, with the error diffused into it already added, and must be total: accumulated error pushes values beyond the nominal range, below 0 or above 255, and the quantizer must still return a sensible value. ditherImage diffuses the difference between the corrected value and the output to the neighbours.

#Context Source

type Context = { x :: Int, y :: Int }

Where the pixel being quantized sits: column x and row y, from 0 at the top-left. A record so it can grow, with a seed say, without breaking quantizers: a helper that needs only some fields can take forall r. { x :: Int, y :: Int | r }.

#threshold Source

threshold :: Number -> Quantize Number

The classic 1-bit quantizer: 0 (black) below the threshold, 255 (white) at or above it.

  • Number: the threshold, usually 128.

nearestLevel (evenRamp 2) is the same with the cut fixed at 127.5.

With a gamma (ditherImageWith), the cut stays at the stored value: it's converted to light once, so a gray below it still goes to black.

#runQuantize Source

runQuantize :: forall a. Quantize a -> Context -> a -> a

Runs a quantizer.

  • Quantize a: the quantizer.
  • Context: the pixel's position.
  • a: the corrected value.

Returns the output value. For many pixels, apply it to the quantizer once and keep the result, let q = runQuantize quantizer, then call q for each pixel: some quantizers prepare things first.

#quantizeWith Source

quantizeWith :: forall a. (Context -> a -> a) -> Quantize a

A quantizer that also gets the pixel's position: ordered or noise dithering, say, or a lookup in per-pixel data such as a mask.

  • Context -> a -> a: from the position and the corrected value to the output value.
-- 1-bit with the cut at 64 and 192 in a checkerboard
quantizeWith \{ x, y } v ->
  if v < (if (x + y) `mod` 2 == 0 then 64.0 else 192.0) then 0.0 else 255.0

With a gamma other than gammaOff, as for quantize: the function still sees stored values, at two conversions per pixel.

#quantize Source

quantize :: forall a. (a -> a) -> Quantize a

A quantizer that ignores the pixel's position, the common case.

  • a -> a: from the corrected value to the output value.
-- 1-bit with the cut at 100
quantize \v -> if v < 100.0 then 0.0 else 255.0

With a gamma other than gammaOff (Puregrain.Dither.ditherImageWith), the function still gets and returns stored values: each pixel is brought back from light before it and its result taken to light after, while the error stays in light. That's two conversions per pixel; a quantizer built with quantizeInLight needs none.

#perChannel Source

perChannel :: forall a. MapChannels a => Quantize Number -> Quantize a

Runs a one-channel quantizer on every channel of a pixel, independently, each with the pixel's position.

  • a: the pixel type, with MapChannels: Number, RGB or RGBA.
  • Quantize Number: the quantizer for one channel.

Dithering an RGB image this way gives exactly what dithering its three channel planes separately would: a Quantize Number only ever sees one channel, so it can't couple them. For a quantizer that looks at the whole pixel, see Puregrain.Palette.nearestColor.

-- 4 levels per channel
perChannel (nearestLevel (evenRamp 4)) :: Quantize RGB

#nearestLevel Source

nearestLevel :: NonEmptyArray Number -> Quantize Number

Snaps a value to the nearest of the given levels: the one-channel sibling of Puregrain.Palette.nearestColor.

  • NonEmptyArray Number: the levels, in any order; on an exact tie, the earlier wins. Levels that aren't whole numbers are rounded first (to 128 for 127.5), so that the error is measured against the value a file stores; of levels made equal by rounding, the earlier counts.

Values below the lowest level snap to it, values above the highest to that one.

nearestLevel (evenRamp 4)   -- 0, 85, 170 or 255

With a gamma (ditherImageWith), a value still takes the level nearest on stored values, while the error stays in light; whole levels come back from light exactly.

#evenRamp Source

evenRamp :: Int -> NonEmptyArray Number

Evenly spaced levels from 0 to 255, both ends included, each rounded to a whole number, the value a file stores: for nearestLevel and Puregrain.Ordered.ordered.

  • Int: how many; 1 or less gives the single middle level, 128.

evenRamp 2 == [0.0, 255.0], evenRamp 3 == [0.0, 128.0, 255.0], evenRamp 4 == [0.0, 85.0, 170.0, 255.0].