Merge pull request #4 from KrisKennaway/shr

Add support for Super Hi-Res conversions
This commit is contained in:
KrisKennaway 2022-07-18 23:06:18 +01:00 committed by GitHub
commit bce2153d97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 1474 additions and 378 deletions

351
README.md
View File

@ -1,15 +1,24 @@
# ][-pix
# ][-pix 2.0
][-pix is an image conversion utility targeting Apple II graphics modes, currently Double Hi-Res.
][-pix is an image conversion utility targeting Apple II graphics modes, currently Double Hi-Res and Super Hi-Res.
## Installation
Requires:
* python 3.x
* [numpy](http://numpy.org/)
* [cython](https://cython.org/)
* [Pillow](https://python-pillow.org/)
* [colour-science](https://www.colour-science.org/)
* [cython](https://cython.org/)
* [numpy](http://numpy.org/)
* [Pillow](https://python-pillow.org/)
* [pygame](https://www.pygame.org/)
* [scikit-learn](https://scikit-learn.org/)
These dependencies can be installed using the following command:
```buildoutcfg
# Install python dependencies
pip install -r requirements.txt
```
To build ][-pix, run the following commands:
@ -17,16 +26,38 @@ To build ][-pix, run the following commands:
# Compile cython code
python setup.py build_ext --inplace
# Precompute RGB/CAM16-UCS colour conversion matrix, used as part of image optimization
# Precompute colour conversion matrices, used as part of image optimization
python precompute_conversion.py
```
## Usage
# Usage
Then, to convert an image, the simplest usage is:
To convert an image, the basic command is:
```bash
python convert.py <mode> [<flags>] <input> <output>
```
where
* `mode` is `dhr` for Double Hi-Res (560x192), or `shr` for Super Hi-Res (320x200)
* `input` is the source image file to convert (e.g. `my-image.jpg`)
* `output` is the output filename to produce (e.g. `my-image.dhr`)
The following flags are supported in both `dhr` and `shr` modes:
* `--show-input` Whether to show the input image before conversion. (default: False)
* `--show-output` Whether to show the output image after conversion. (default: True)
* `--save-preview` Whether to save a .PNG rendering of the output image (default: True)
* `--verbose` Show progress during conversion (default: False)
* `--gamma-correct` Gamma-correct image by this value (default: 2.4)
See below for DHR- and SHR- specific instructions.
## Double Hi-Res
To convert an image to Double Hi-Res (560x192, 16 colours but [it's complicated](docs/dhr.md)), the simplest usage is:
```buildoutcfg
python convert.py --palette ntsc <input> <output.dhr>
python convert.py dhr --palette ntsc <input> <output.dhr>
```
`<output.dhr>` contains the double-hires image data in a form suitable for transfer to an Apple II disk image. The 16k output consists of 8k AUX data first, 8K MAIN data second (this matches the output format of other DHGR image converters). i.e. if loaded at 0x2000, the contents of 0x2000..0x3fff should be moved to 0x4000..0x5fff in AUX memory, and the image can be viewed on DHGR page 2.
@ -37,9 +68,29 @@ For other available options, use `python convert.py --help`
TODO: document flags
## Examples
For more details about Double Hi-Res graphics and the conversion process, see [here](docs/dhr.md).
See [here](examples/gallery.md) for more sample image conversions.
## Super Hi-Res
To convert an image to Super Hi-Res (320x200, up to 256 colours), the simplest usage is:
```buildoutcfg
python convert.py shr <input> <output.shr>
```
i.e. no additional options are required. In addition to the common flags described above, these additional flags are
supported for `shr` conversions:
* `--save-intermediate` Whether to save each intermediate iteration, or just the final image (default: False)
* `--fixed-colours` How many colours to fix as identical across all 16 SHR palettes. (default: 0)
* `--show-final-score` Whether to output the final image quality score (default: False)
TODO: link to KansasFest 2022 talk slides/video for more details
# Examples
## Double Hi-Res
See [here](examples/gallery.md) for more sample Double Hi-Res image conversions.
### Original
@ -73,285 +124,25 @@ This is an OpenEmulator screenshot of the same image converted with `--palette=n
![Two colourful parrots sitting on a branch](examples/parrots-iipix-ntsc-openemulator.png)
## Super Hi-Res
## Some background on Apple II Double Hi-Res graphics
Like other (pre-//gs) Apple II graphics modes, Double Hi-Res relies on [NTSC Artifact Colour](https://en.wikipedia.org/wiki/Composite_artifact_colors), which means that the colour of a pixel is entirely determined by its horizontal position on the screen, and the on/off status of preceding horizontal pixels.
In Double Hi-Res mode, the 560 horizontal pixels per line are individually addressable. This is an improvement over the (single) Hi-Res mode, which also has 560 horizontal pixels, but which can only be addressed in groups of two (with an option to shift blocks of 7 pixels each by one dot). See _Assembly Lines: The Complete Book_ (Wagner) for a detailed introduction to this, or _Understanding the Apple IIe_ (Sather) for a deep technical discussion.
Double Hi-Res is usually characterized as being capable of producing 16 display colours, but with heavy restrictions on how these colours can be arranged horizontally.
### Naive model: 140x192x16
One simple model for Double Hi-Res graphics is to only treat the display in groups of 4 horizontal pixels, which gives an effective resolution of 140x192 in 16 colours (=2^4). These 140 pixel colours can be chosen independently, which makes this model easy to think about and to work with (e.g. when creating images by hand). However the resulting images will exhibit (sometimes severe) colour interference/fringing effects when two colours are next to one another, because the underlying hardware does not actually work this way. See below for an example image conversion, showing the unwanted colour fringing that results.
### Simplest realistic model: 560 pixels, 4-pixel colour
A more complete model for thinking about DHGR comes from looking at how the NTSC signal produces colour on the display.
The [NTSC chrominance subcarrier](https://en.wikipedia.org/wiki/Chrominance_subcarrier) completes one complete phase cycle in the time taken to draw 4 horizontal dots. The colours produced are due to the interactions of the pixel luminosity (on/off) relative to this NTSC chroma phase.
What this means is that the colour of each of the 560 horizontal pixels is determined by the current pixel value (on/off), the current X-coordinate modulo 4 (X coordinate relative to NTSC phase), as well as the on-off status of the pixels to the left of it.
The simplest approximation is to only look at the current pixel value and the 3 pixels to the left, i.e. to consider a sliding window of 4 horizontal pixels moving across the screen from left to right. Within this window, we have one pixel for each of the 4 values of NTSC phase (x % 4, ranging from 0 .. 3). The on-off values for these 4 values of NTSC phase determine the colour of the pixel. See [here](https://docs.google.com/presentation/d/1_eqBknG-4-llQw3oAOmPO3FlawUeWCeRPYpr_mh2iRU/edit) for more details.
This model allows us to understand and predict the interference behaviour when two "140px" colours are next to each other, and to go beyond this "140px" model to take more advantage of the true 560px horizontal resolution.
If we imagine drawing pixels from left to right across the screen, at each pixel we only have *two* accessible choices of colour: those resulting from turning the current pixel on, or off. Which two particular colours are produced are determined by the pixels already drawn to the left (the immediate 3 neighbours, in our model). One of these possibilities will always be the same as the pixel colour to the left (the on/off pixel choice corresponding to the value that just "fell off the left side" of the sliding window), and the other choice is some other colour from our palette of 16.
This can be summarized in a chart, showing the possible colour transitions depending on the colour of the pixel to the immediate left, and the value of x%4.
![Double hi-res colour transitions](docs/Double_Hi-Res_colour_transitions.png)
So, if we want to transition from one colour to a particular new colour, it may take up to 4 horizontal pixels before we are able to achieve it (e.g. transitioning all the way from black (0000) to white (1111)). In the meantime we have to transition through up to 2 other colours. Depending on the details of the image we are aiming for, this may either produce unwanted visual noise, or can actually be beneficial (e.g. if the colour we want is available immediately at the next pixel)
These constraints are difficult to work with when constructing DHGR graphics "by hand", but we can account for them programmatically in our image conversion to take full advantage of the "true" 560px resolution while accounting for colour interference effects.
#### Limitations of this colour model
In practise the above description of the Apple II colour model is still only an approximation. On real hardware, the video signal is a continuous analogue signal, and colour is continuously modulated rather than producing discretely-coloured pixels with fixed colour values.
More importantly, in an NTSC video signal the colour (chroma) signal has a lower bandwidth than the luma (brightness) signal ([Chroma sub-sampling](https://en.wikipedia.org/wiki/Chroma_subsampling)), which means that colours will tend to bleed across more than 4 pixels. However our simple "4-pixel chroma bleed" model already produces good results, and exactly matches the implementation behaviour of some emulators, e.g. Virtual II.
### NTSC emulation and 8-pixel colour
By simulating the NTSC (Y'UV) signal directly we are able to recover the Apple II colour output from "first principles". Here are the 16 "basic" DHGR colours, obtained using saturation/hue parameters tuned to match OpenEmulator's NTSC implementation, and allowing chroma to bleed across 4 pixels.
![NTSC colours with 4 pixel chroma bleed](docs/ntsc-colours-chroma-bleed-4.png)
However in real NTSC, chroma bleeds over more than 4 pixels, which means that we actually have more than 2^4 colours available to work with.
This means that **when viewed on a composite colour display, Double Hi-Res graphics is not just a 16-colour graphics mode!**
If we allow the NTSC chroma signal to bleed over 8 pixels instead of 4, then the resulting colour is determined by sequences of 8 pixels instead of 4 pixels, i.e. there are 2^8 = 256 possibilities. In practise many of these result in the same output colour, and (with this approximation) there are only 85 unique colours available. However this is still a marked improvement on the 16 "basic" DHGR colours:
![NTSC colours with 8 pixel chroma bleed](docs/ntsc-colours-chroma-bleed-8.png)
The "extra" DHGR colours are only available on real hardware, or an emulator that implements NTSC chroma sub-sampling (such as OpenEmulator). But the result is that on such targets a much larger range of colours is available for use in image conversion. However the restriction still exists that any given pixel only has a choice of 2 colours available (as determined by the on/off state of pixels to the left).
In practise this gives much better image quality, especially when shading areas of similar colour. The Apple II is still unable to directly modulate the luma (brightness) NTSC signal component, so areas of low or high brightness still tend to be heavily dithered. This is because there are more bit sequences that have the number of '1' bits close to the average than there are at the extremes, so there are correspondingly few available colours that are very bright or very dark.
These 85 unique double hi-res colours produced by the ][-pix NTSC emulation are not the definitive story - though they're closer to it than the usual story that double hi-res is a 16-colour graphics mode. The implementation used by ][-pix is the simplest one: the Y'UV signal is averaged with a sliding window of 4 pixels for the Y' (luma) component and 8 pixels for the UV (chroma) component.
The choice of 8 pixels is not strictly correct - e.g. the chroma bandwidth (~0.6MHz) is much less than half of luma bandwidth (~2Mhz) so the signal bleeds over more than twice as many pixels; but also decays in a more complex way than the simple step function sliding window chosen here. In practise using 8 pixels is a good compromise between ease of implementation, runtime performance and fidelity.
By contrast, OpenEmulator uses a more complex (and realistic) band-pass filtering to produce its colour output, which presumably allows even more possible colours (physical hardware will also produce its own unique results, depending on the hardware implementation of the signal decoding, and other physical characteristics). I expect that most of these will be small variations on the above though; and in practise the ][-pix NTSC implementation already produces a close colour match for the OpenEmulator behaviour.
#### Examples of NTSC images
(Source: [Reinhold Möller](https://commons.wikimedia.org/wiki/File:Nymphaea_caerulea-20091014-RM-115245.jpg), [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0), via Wikimedia Commons)
![Nymphaea](examples/nymphaea-original.png)
OpenEmulator screenshot of image produced with `--palette=openemulator --lookahead=8`. The distorted background colour compared to the original is particularly noticeable.
![Nymphaea](examples/nymphaea-iipix-openemulator-openemulator.png)
OpenEmulator screenshot of image produced with `--palette=ntsc --lookahead=8`. Not only is the background colour a much better match, the image shading and detail is markedly improved.
![Nymphaea](examples/nymphaea-iipix-ntsc-openemulator.png)
Rendering the same .dhr image with 4-pixel colour shows the reason for the difference. For example the background shading is due to pixel sequences that appear (with this simpler and less hardware-accurate rendering scheme) as sequences of grey and dark green, with a lot of blue and red sprinkled in. In NTSC these pixel sequences combine to produce various shades of green.
![Nymphaea](examples/nymphaea-iipix-ntsc-preview-openemulator.png)
# Dithering and Double Hi-Res
[Dithering](https://en.wikipedia.org/wiki/Dither) an image to produce an approximation with fewer image colours is a well-known technique. The basic idea is to pick a "best colour match" for a pixel from our limited palette, then to compute the difference between the true and selected colour values and diffuse this error to nearby pixels (using some pattern).
In the particular case of DHGR this algorithm runs into difficulties, because each pixel only has two possible colour choices (from a total of 16+). If we only consider the two possibilities for the immediate next pixel then neither may be a particularly good match. However it may be more beneficial to make a suboptimal choice now (deliberately introduce more error), if it allows us access to a better colour for a subsequent pixel. "Classical" dithering algorithms do not account for these palette constraints, and produce suboptimal image quality for DHGR conversions.
We can deal with this by looking ahead N pixels (8 by default) for each image position (x,y), and computing the effect of choosing all 2^N combinations of these N-pixel states on the dithered source image.
Specifically, for a fixed choice of one of these N pixel sequences, we tentatively perform the error diffusion as normal on a copy of the image, and compute the total mean squared distance from the (fixed) N-pixel sequence to the error-diffused source image. To compute the perceptual difference between colours we convert to the perceptually uniform [CAM16-UCS](https://en.wikipedia.org/wiki/Color_appearance_model#CAM16) colour space in which perceptual distance is Euclidean.
Finally, we pick the N-pixel sequence with the lowest total error, and select the first pixel of this N-pixel sequence for position (x,y). We then perform error diffusion as usual for this single pixel, and proceed to x+1.
This allows us to "look beyond" local minima to find cases where it is better to make a suboptimal choice now to allow better overall image quality in subsequent pixels. Since we will sometimes find that our choice of 2 next-pixel colours actually includes (or comes close to) the "ideal" choice, this means we can take maximal advantage of the 560-pixel horizontal resolution.
## Gamma correction
Most digital images are encoded using the [sRGB colour space](https://en.wikipedia.org/wiki/SRGB), which means that the stored RGB values do not map linearly onto the rendered colour intensities. In order to work with linearized RGB values the source image needs to be gamma corrected. Otherwise, the process of dithering an un-gamma-corrected image tends to result in an output that does not match the brightness of the input. In particular shadows and highlights tend to get blown out/over-exposed.
## Dither pattern
The process of (error-diffusion) dithering involves distributing the "quantization error" (mismatch between the colour of the source image and chosen output pixels) across neighbouring pixels, according to some pattern. [Floyd-Steinberg](https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering) and [Jarvis-Judice-Ninke](https://en.wikipedia.org/wiki/Error_diffusion#minimized_average_error) ("Jarvis") are two common patterns, though there are many others, which have slightly different characteristics.
Since it uses a small dither pattern, Floyd-Steinberg dithering retains more of the image detail than larger kernels. On the other hand, it sometimes produces image artifacts that are highly structured (e.g. runs of a single colour, checkerboard patterns). This seems to be especially common with 4-pixel colours.
In part this may be because these "classical" dither patterns only propagate errors to a small number of neighbouring pixels, e.g. 1 pixels in the forward direction for Floyd-Steinberg, and 2 pixels for Jarvis. However for double hi-res colours we know that it might take up to 4 pixels before a given colour can be selected for output (e.g. to alternate between black and white, or any other pairs that are 4 steps away on the transition chart above).
In other words, given the results of error diffusion from our current pixel, there is one colour from our palette of 16 that is the best one to match this - but it might be only possible to render this particular colour up to 4 pixels further on. If we only diffuse the errors by 1 or 2 pixels each time, it will tend to have diffused away by the time we reach that position, and the opportunity will be lost. Combined with the small overall set of available colours this can result in image artifacts.
Modifying the Jarvis dither pattern to extend 4 pixels in the forward direction seems to give much better results for such images (e.g. when dithering large blocks of colour), although at the cost of reduced detail. This is presumably because we allow each quantization error to diffuse to each of the 4 subsequent pixels that might be best-placed to act on it.
The bottom line is that choice of `--dither` argument is a tradeoff between image detail and handling of colour. If the default `--dither=floyd` algorithm does not give pleasing results, try other patterns such as `--dither=jarvis-mod`.
Further experimentation with other dithering patterns (and similar modifications to the above) may also produce interesting results.
## Palettes
Since the Apple II graphics (prior to //gs) are not based on RGB colour, we have to choose an (approximate) RGB colour palette when dithering an RGB image. There is no "true" choice for this palette, since it depends heavily on how the image is viewed:
1. Different emulators have made (often quite different) choices for the RGB colour palettes used to emulate Apple II graphics on a RGB display. This means that an image that looks good on one emulator may not look good on another (or on real hardware).
- For example, Virtual II (and the Apple //gs) uses two different RGB shades of grey for the two DHGR grey colours, whereas they are rendered identically in NTSC. That means that images not targeted for the Virtual II palette will look quite different when viewed there (and vice versa).
2. Secondly, the actual display colours rendered by an Apple II are not fixed, but bleed into each other due to the behaviour of the (analogue) NTSC video signal. i.e. the entire notion of a "16-colour RGB palette" is a flawed one. Furthermore, the NTSC colours depend on the particular monitor/TV and its tuning (brightness/contrast/hue settings etc). "Never Twice the Same Colour" indeed. The "4-pixel colour" model described above where we can assign 2 from 16 fixed colours to each of 560 discrete pixels is only an approximation (though a useful one in practise).
Some emulators emulate the NTSC video signal more faithfully (e.g. OpenEmulator), in which case they do not have a true "RGB palette". The best we can do here is measure the colours that are produced by large blocks of colour, i.e. where there is no colour blending. Others use some discrete approximation (e.g. Virtual II seems to exactly match the colour model described above), so a fixed palette can be reconstructed.
To compute the emulator palettes used by ][-pix I measured the sRGB colour values produced by a full-screen Apple II colour image (using the colour picker tool of Mac OS X), using default emulator settings. I have not yet attempted to measure/estimate palettes of other emulators, or "real hardware"
Existing conversion tools (see below) tend to support a variety of RGB palette values sourced from various places (older tools, emulators, theoretical estimations etc). In practise, these only matter in a few ways:
1. If you are trying to target colour balance as accurately as possible for a particular viewing target (e.g. emulator), i.e. so that the rendered colour output looks as close as possible to the source image.
2. If you are targeting an emulator that has a "non-standard" colour model, e.g. Virtual II with its two distinct shades of grey.
3. Otherwise, choices of palette effectively amount to changing the colour balance of the source image. Some of these might produce better image quality for a particular image (e.g. if the source image contains large colour blocks that are difficult to approximate with a particular target palette), at the cost of changing the colour balance. i.e. it might look good on its own but not match the source image. You could also achieve similar results by tweaking the colour balance of the source image in an editor, e.g GIMP or Photoshop.
## Precomputing distance matrix
The mapping from RGB colour space to CAM16-UCS is quite complex, so to avoid this runtime cost we precompute a matrix from all 256^3 integer RGB values to corresponding CAM16-UCS values. This 192MB matrix is generated by the `precompute_conversion.py` utility, and is loaded at runtime for efficient access.
# Comparison to other DHGR image converters
## bmp2dhr
* [bmp2dhr](http://www.appleoldies.ca/bmp2dhr/) (see [here](https://github.com/digarok/b2d) for a maintained code fork) supports additional graphics modes not yet supported by ][-pix, namely (double) lo-res, and hi-res. Support for the lores modes would be easy to add to ][-pix, although hi-res requires more work to accommodate the colour model. A similar lookahead strategy will likely work well though.
* supports additional image dither modes
* only supports BMP source images in a particular format.
* DHGR conversions are treated as simple 140x192x16 colour images without colour constraints, and ignores the colour fringing behaviour described above. The generated .bmp preview images also do not show fringing, but it is present when viewing the image on an Apple II or emulator that accounts for it. i.e. the preview images are sometimes not very representative of the actual results. See below for an example.
* Apart from ignoring DHGR colour interactions, the 140px converted images are also lower than ideal resolution since they do not make use of the ability to address all 560px independently.
* The perceptual colour distance metric used to match the best colour to an input pixel is a custom metric based on a weighted sum of Euclidean sRGB distance and Rec.601 luma value. It's not explained why this particular metric was chosen, and in practise it seems to often give much lower quality results than modern perceptually uniform colour spaces like CIE2000 or CAM16-UCS (though these are much slower to compute - which is why we precompute the conversion matrix ahead of time)
* It does not perform RGB colour space conversions before dithering, i.e. if the input image is in sRGB colour space (as most digital images will be) then the dithering is also performed in sRGB. Since sRGB is not a linear colour space, the effect of dithering is to distribute errors non-linearly, which distorts the brightness of the resulting image.
## a2bestpix
* Like ][-pix, [a2bestpix](http://lukazi.blogspot.com/2017/03/double-high-resolution-graphics-dhgr.html) only supports DHGR conversion. Overall quality is usually fairly good, although colours and brightness are slightly distorted (for reasons described below), and the generated preview images do not quite give a faithful representation of the native image rendering.
* Like ][-pix, and unlike bmp2dhr, a2bestpix does apply a model of the DHGR colour interactions, albeit an ad-hoc one based on rules and tables of 4-pixel "colour blocks" reconstructed from (AppleWin) emulator behaviour. This does allow it to make use of (closer to) full 560px resolution, although it still treats the screen as a sequence of 140 4-pixel colour blocks (with some constraints on the allowed arrangement of these blocks).
* supports additional (custom) dither modes (partly out of necessity due to the custom "colour block" model)
* Supports a variety of perceptual colour distance metrics including CIE2000 and the one bmp2dhr uses. In practise I'm not sure the others are useful since CIE2000 is the more recent refinement of much research on this topic, and is the most accurate of them.
* like bmp2dhr, only supports BMP source images in a particular format.
* Does not apply gamma correction before dithering (though sRGB conversion is done when computing CIE2000 distance), so errors are diffused non-linearly. The resulting images don't match the brightness of the original, e.g. shadows/highlights tend to be over-exposed.
* image conversion performs an optimization over groups of multiple pixels (via choice of "colour blocks"). From what I can tell this minimizes the total colour distance from a fixed list of colour blocks to a group of 4 target pixels, similar to --lookahead=4 for ][-pix (though I'm not sure it's evaluating all 2^4 pixel combinations). But since the image is (AFAICT) treated as a sequence of (non-overlapping) 4-pixel blocks this does not result in optimizing each output pixel independently.
* The list of "colour blocks" seem to contain colour sequences that cannot actually be rendered on the Apple II. For example compare the spacing of yellow and orange pixels on the parrot between the preview image (LHS) and openemulator (RHS):
![Detail of a2bestpix preview image](docs/a2bestbix-preview-crop.png)
![Detail of openemulator render](docs/a2bestpix-openemulator-crop.png)
* See below for another example where the output has major image discrepancies with the original - perhaps also due to bugs/omissions in the table of colour blocks.
* This means that (like bmp2dhr) the generated "preview" image may not closely match the native image, and the dithering algorithm is also optimizing over a slightly incorrect set of colour sequences, which presumably impacts image quality. Possibly these are transcription errors, or artifacts of the particular emulator (AppleWin) from which they were reconstructed.
## Image comparisons
These three images were converted using the same target (openemulator) palette, using ][-pix, bmp2dhr and a2bestpix (since this is supported by all three), and are shown as screenshots from openemulator.
### Original
![original source image](examples/paperclips-original.png)
(Source: [Purple Sherbet Photography from Worldwide!](https://commons.wikimedia.org/wiki/File:Colourful_assortment_of_paper_clips_(10421946796).jpg), [CC BY 2.0](https://creativecommons.org/licenses/by/2.0), via Wikimedia Commons)
The following images were all generated with a palette approximating OpenEmulator's colours (`--palette=openemulator` for ][-pix)
### ][-pix 4-pixel colour
Preview image and OpenEmulator screenshot
![ii-pix preview](examples/paperclips-iipix-openemulator-preview.png)
![ii-pix screenshot](examples/paperclips-iipix-openemulator-openemulator.png)
### ][-pix NTSC 8-pixel colour (Preview image)
Preview image and OpenEmulator screenshot
![ii-pix preview](examples/paperclips-iipix-ntsc-preview.png)
![ii-pix screenshot](examples/paperclips-iipix-ntsc-openemulator.png)
### bmp2dhr (OpenEmulator screenshot)
![bmp2dhr screenshot](examples/paperclips-bmp2dhr-openemulator.png)
Comparing bmp2dhr under openemulator is the scenario most favourable to it, since the 140px resolution and non-treatment of fringing is masked by the chroma blending. Colours are similar to ][-pix, but the 140px dithering and lack of gamma correction results in less detail, e.g. in hilights/shadows.
### a2bestpix (OpenEmulator screenshot)
![a2bestpix screenshot](examples/paperclips-a2bestpix-openemulator.png)
This a2bestpix image is actually atypical in quality, and shows some severe colour errors relating to the pixels that should be close to the orange/brown colours. These may be due to errors/omissions in the set of "colour blocks". The effects of not gamma-correcting the source image can also be seen.
## NTSC artifacts
The difference in treatment of NTSC artifacts is much more visible when using an emulator that doesn't perform chroma subsampling, e.g. Virtual II. i.e. it displays the full 560-pixel colour image without blending.
### Original
![original source image](examples/groundhog-original.png)
(Source: [Cephas](https://commons.wikimedia.org/wiki/File:Marmota_monax_UL_04.jpg), [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0), via Wikimedia Commons)
The following images were generated with a palette matching the one used by Virtual II (`--palette=virtualii` for ][-pix)
### ][-pix
![original source image](examples/groundhog-original.png)
![ii-pix preview](examples/groundhog-iipix-virtualii-preview.png)
### bmp2dhr
![original source image](examples/groundhog-original.png)
![ii-pix screenshot](examples/groundhog-bmp2dhr-virtualii.png)
The image is heavily impacted by colour fringing, which bmp2dhr does not account for at all. The difference in brightness of the groundhog's flank is also because bmp2dhr does not gamma-correct the image, so shadows/highlights tend to get blown out.
### bmp2dhr (OpenEmulator)
![original source image](examples/groundhog-original.png)
![ii-pix screenshot](examples/groundhog-bmp2dhr-openemulator.png)
This bmp2dhr image was generated using a palette approximating OpenEmulator's colours (`--palette=openemulator` for ][-pix), i.e. not the same image files as above.
On OpenEmulator, which simulates NTSC chroma sub-sampling, the fringing is not pronounced but changes the colour balance of the image, e.g. creates a greenish tinge.
### ][-pix, 4-pixel colour (OpenEmulator)
![original source image](examples/groundhog-original.png)
![ii-pix screenshot](examples/groundhog-iipix-openemulator-openemulator.png)
Colour balance here is also slightly distorted due to not fully accounting for chroma blending.
### ][-pix, NTSC 8-pixel colour (OpenEmulator)
![original source image](examples/groundhog-original.png)
![ii-pix screenshot](examples/groundhog-iipix-ntsc-openemulator.png)
Detail and colour balance is much improved.
TODO: add example images
# Future work
* Supporting lo-res and double lo-res graphics modes would be straightforward.
* Supporting lo-res and double lo-res graphics modes, and super hi-res 3200 modes would be straightforward.
* Hi-res will require more care, since the 560 pixel display is not individually dot addressible. In particular the behaviour of the "palette bit" (which shifts a group of 7 dots to the right by 1) is another optimization constraint. In practise a similar lookahead algorithm should work well though.
* Super hi-res 640 mode would also likely require some investigation, since it is a more highly constrained optimization problem than 320 mode.
* I would like to be able to find an ordered dithering algorithm that works well for Apple II graphics. Ordered dithering specifically avoids diffusing errors arbitrarily across the image, which produces visual noise (and unnecessary deltas) when combined with animation. For example such a thing may work well with my [II-Vision](https://github.com/KrisKennaway/ii-vision) video streamer. However the properties of NTSC artifact colour seem to be in conflict with these requirements, i.e. pixel changes *always* propagate colour to some extent.
# Version history
## v1.0 (2021-03-15)
## v2.0 (2022-07-16)
Initial release
* Added support for Super Hi-Res 320x200 image conversions
## v1.1 (2021-11-05)
@ -362,4 +153,8 @@ Initial release
* Switch default to --dither=floyd, which seems to produce the best results with --palette=ntsc
* Various internal code simplifications and cleanups
## v1.0 (2021-03-15)
Initial release
![me](examples/kris-iipix-openemulator.png)

5
common.pxd Normal file
View File

@ -0,0 +1,5 @@
cdef float clip(float a, float min_value, float max_value) nogil
cdef float[::1] convert_rgb_to_cam16ucs(float[:, ::1] rgb_to_cam16ucs, float r, float g, float b) nogil
cdef double colour_distance_squared(float[::1] colour1, float[::1] colour2) nogil

23
common.pyx Normal file
View File

@ -0,0 +1,23 @@
# cython: infer_types=True
# cython: profile=False
# cython: boundscheck=False
# cython: wraparound=False
cdef float clip(float a, float min_value, float max_value) nogil:
"""Clip a value between min_value and max_value inclusive."""
return min(max(a, min_value), max_value)
cdef inline float[::1] convert_rgb_to_cam16ucs(float[:, ::1] rgb_to_cam16ucs, float r, float g, float b) nogil:
"""Converts floating point (r,g,b) valueto 3-tuple in CAM16UCS colour space, via 24-bit RGB lookup matrix."""
cdef unsigned int rgb_24bit = (<unsigned int>(r*255) << 16) + (<unsigned int>(g*255) << 8) + <unsigned int>(b*255)
return rgb_to_cam16ucs[rgb_24bit]
cdef inline double colour_distance_squared(float[::1] colour1, float[::1] colour2) nogil:
"""Computes Euclidean squared distance between two floating-point colour 3-tuples."""
return (colour1[0] - colour2[0]) ** 2 + (colour1[1] - colour2[1]) ** 2 + (colour1[2] - colour2[2]) ** 2

View File

@ -1,39 +1,27 @@
"""Image converter to Apple II Double Hi-Res format."""
import argparse
import os.path
import time
import colour
from PIL import Image
import numpy as np
import dither as dither_pyx
import convert_dhr as convert_dhr_py
import convert_shr as convert_shr_py
import dither_pattern
import image as image_py
import palette as palette_py
import screen as screen_py
# TODO:
# - support LR/DLR
# - support HGR
# - support additional graphics modes (easiest --> hardest):
# - LR/DLR
# - SHR 3200
# - SHR 640
# - HGR
def main():
parser = argparse.ArgumentParser()
def add_common_args(parser):
parser.add_argument("input", type=str, help="Input image file to process.")
parser.add_argument("output", type=str, help="Output file for converted "
"Apple II image.")
parser.add_argument(
"--lookahead", type=int, default=8,
help=("How many pixels to look ahead to compensate for NTSC colour "
"artifacts (default: 8)"))
parser.add_argument(
'--dither', type=str, choices=list(dither_pattern.PATTERNS.keys()),
default=dither_pattern.DEFAULT_PATTERN,
help="Error distribution pattern to apply when dithering (default: "
+ dither_pattern.DEFAULT_PATTERN + ")")
parser.add_argument(
'--show-input', action=argparse.BooleanOptionalAction, default=False,
help="Whether to show the input image before conversion.")
@ -41,6 +29,43 @@ def main():
'--show-output', action=argparse.BooleanOptionalAction, default=True,
help="Whether to show the output image after conversion.")
parser.add_argument(
'--save-preview', action=argparse.BooleanOptionalAction, default=True,
help='Whether to save a .PNG rendering of the output image (default: '
'True)'
)
parser.add_argument(
'--verbose', action=argparse.BooleanOptionalAction,
default=False, help="Show progress during conversion")
parser.add_argument(
'--gamma-correct', type=float, default=2.4,
help='Gamma-correct image by this value (default: 2.4)'
)
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(required=True)
dhr_parser = subparsers.add_parser("dhr")
add_common_args(dhr_parser)
def validate_lookahead(arg: int) -> int:
try:
int_arg = int(arg)
if int_arg < 1:
return int_arg
except Exception:
raise argparse.ArgumentTypeError("--lookahead must be at least 1")
dhr_parser.add_argument(
"--lookahead", type=validate_lookahead, default=8,
help=("How many pixels to look ahead to compensate for NTSC colour "
"artifacts (default: 8)"))
dhr_parser.add_argument(
'--dither', type=str, choices=list(dither_pattern.PATTERNS.keys()),
default=dither_pattern.DEFAULT_PATTERN,
help="Error distribution pattern to apply when dithering (default: "
+ dither_pattern.DEFAULT_PATTERN + ")")
dhr_parser.add_argument(
'--palette', type=str, choices=list(set(palette_py.PALETTES.keys())),
default=palette_py.DEFAULT_PALETTE,
help='RGB colour palette to dither to. "ntsc" blends colours over 8 '
@ -48,64 +73,58 @@ def main():
'use/emulate NTSC, but can be substantially slower. Other '
'palettes determine colours based on 4 pixel sequences '
'(default: ' + palette_py.DEFAULT_PALETTE + ")")
parser.add_argument(
dhr_parser.add_argument(
'--show-palette', type=str, choices=list(palette_py.PALETTES.keys()),
help="RGB colour palette to use when --show_output (default: "
"value of --palette)")
parser.add_argument(
'--verbose', action=argparse.BooleanOptionalAction,
default=False, help="Show progress during conversion")
parser.add_argument(
'--gamma_correct', type=float, default=2.4,
help='Gamma-correct image by this value (default: 2.4)'
dhr_parser.set_defaults(func=convert_dhr)
shr_parser = subparsers.add_parser("shr")
add_common_args(shr_parser)
shr_parser.add_argument(
'--fixed-colours', type=int, default=0,
help='How many colours to fix as identical across all 16 SHR palettes '
'(default: 0)'
)
shr_parser.add_argument(
'--show-final-score', action=argparse.BooleanOptionalAction,
default=False, help='Whether to output the final image quality score '
'(default: False)'
)
shr_parser.add_argument(
'--save-intermediate', action=argparse.BooleanOptionalAction,
default=False, help='Whether to save each intermediate iteration, '
'or just the final image (default: False)'
)
shr_parser.set_defaults(func=convert_shr)
args = parser.parse_args()
if args.lookahead < 1:
parser.error('--lookahead must be at least 1')
args.func(args)
palette = palette_py.PALETTES[args.palette]()
screen = screen_py.DHGRScreen(palette)
# Conversion matrix from RGB to CAM16UCS colour values. Indexed by
# 24-bit RGB value
rgb_to_cam16 = np.load("data/rgb_to_cam16ucs.npy")
def prepare_image(image_filename: str, show_input: bool, screen,
gamma_correct: float) -> np.ndarray:
# Open and resize source image
image = image_py.open(args.input)
if args.show_input:
image_py.resize(image, screen.X_RES, screen.Y_RES * 2,
srgb_output=True).show()
image = image_py.open(image_filename)
if show_input:
image_py.resize(image, screen.X_RES, screen.Y_RES,
srgb_output=False).show()
rgb = np.array(
image_py.resize(image, screen.X_RES, screen.Y_RES,
gamma=args.gamma_correct)).astype(np.float32) / 255
gamma=gamma_correct)).astype(np.float32) / 255
return rgb
dither = dither_pattern.PATTERNS[args.dither]()
bitmap = dither_pyx.dither_image(
screen, rgb, dither, args.lookahead, args.verbose, rgb_to_cam16)
# Show output image by rendering in target palette
output_palette_name = args.show_palette or args.palette
output_palette = palette_py.PALETTES[output_palette_name]()
output_screen = screen_py.DHGRScreen(output_palette)
if output_palette_name == "ntsc":
output_srgb = output_screen.bitmap_to_image_ntsc(bitmap)
else:
output_srgb = image_py.linear_to_srgb(
output_screen.bitmap_to_image_rgb(bitmap)).astype(np.uint8)
out_image = image_py.resize(
Image.fromarray(output_srgb), screen.X_RES, screen.Y_RES * 2,
srgb_output=True)
def convert_dhr(args):
palette = palette_py.PALETTES[args.palette]()
screen = screen_py.DHGRScreen(palette)
rgb = prepare_image(args.input, args.show_input, screen, args.gamma_correct)
convert_dhr_py.convert(screen, rgb, args)
if args.show_output:
out_image.show()
# Save Double hi-res image
outfile = os.path.join(os.path.splitext(args.output)[0] + "-preview.png")
out_image.save(outfile, "PNG")
screen.pack(bitmap)
with open(args.output, "wb") as f:
f.write(bytes(screen.aux))
f.write(bytes(screen.main))
def convert_shr(args):
screen = screen_py.SHR320Screen()
rgb = prepare_image(args.input, args.show_input, screen, args.gamma_correct)
convert_shr_py.convert(screen, rgb, args)
if __name__ == "__main__":

48
convert_dhr.py Normal file
View File

@ -0,0 +1,48 @@
import os.path
from PIL import Image
import numpy as np
import dither_dhr as dither_dhr_pyx
import dither_pattern
import palette as palette_py
import screen as screen_py
import image as image_py
def convert(screen: screen_py.DHGRScreen, rgb: np.ndarray, args):
# Conversion matrix from RGB to CAM16UCS colour values. Indexed by
# 24-bit RGB value
base_dir = os.path.dirname(__file__)
rgb24_to_cam16ucs = np.load(
os.path.join(base_dir, "data/rgb24_to_cam16ucs.npy"))
dither = dither_pattern.PATTERNS[args.dither]()
bitmap = dither_dhr_pyx.dither_image(
screen, rgb, dither, args.lookahead, args.verbose, rgb24_to_cam16ucs)
# Show output image by rendering in target palette
output_palette_name = args.show_palette or args.palette
output_palette = palette_py.PALETTES[output_palette_name]()
output_screen = screen_py.DHGRScreen(output_palette)
if output_palette_name == "ntsc":
output_srgb = output_screen.bitmap_to_image_ntsc(bitmap)
else:
output_srgb = image_py.linear_to_srgb(
output_screen.bitmap_to_image_rgb(bitmap)).astype(np.uint8)
out_image = image_py.resize(
Image.fromarray(output_srgb), screen.X_RES, screen.Y_RES * 2,
srgb_output=True)
if args.show_output:
out_image.show()
if args.save_preview:
# Save Double hi-res image
outfile = os.path.join(
os.path.splitext(args.output)[0] + "-preview.png")
out_image.save(outfile, "PNG")
screen.pack(bitmap)
with open(args.output, "wb") as f:
f.write(bytes(screen.aux))
f.write(bytes(screen.main))

457
convert_shr.py Normal file
View File

@ -0,0 +1,457 @@
from collections import defaultdict
import os.path
import random
from typing import Tuple
from PIL import Image
import colour
import numpy as np
from sklearn import cluster
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
import dither_shr as dither_shr_pyx
import image as image_py
class ClusterPalette:
def __init__(
self, image: np.ndarray, rgb12_iigs_to_cam16ucs, rgb24_to_cam16ucs,
fixed_colours=0):
# Conversion matrix from 12-bit //gs RGB colour space to CAM16UCS
# colour space
self._rgb12_iigs_to_cam16ucs = rgb12_iigs_to_cam16ucs
# Conversion matrix from 24-bit linear RGB colour space to CAM16UCS
# colour space
self._rgb24_to_cam16ucs = rgb24_to_cam16ucs
# Preprocessed source image in 24-bit linear RGB colour space. We
# first dither the source image using the full 12-bit //gs RGB colour
# palette, ignoring SHR palette limitations (i.e. 4096 independent
# colours for each pixel). This gives much better results for e.g.
# solid blocks of colour, which would be dithered inconsistently if
# targeting the source image directly.
self._image_rgb = self._perfect_dither(image)
# Preprocessed source image in CAM16UCS colour space
self._colours_cam = self._image_colours_cam(self._image_rgb)
# We fit a 16-colour palette against the entire image which is used
# as starting values for fitting the reserved colours in the 16 SHR
# palettes.
self._global_palette = np.empty((16, 3), dtype=np.uint8)
# How many image colours to fix identically across all 16 SHR
# palettes. These are taken to be the most prevalent colours from
# _global_palette.
self._fixed_colours = fixed_colours
# 16 SHR palettes each of 16 colours, in CAM16UCS colour space
self._palettes_cam = np.empty((16, 16, 3), dtype=np.float32)
# 16 SHR palettes each of 16 colours, in //gs 4-bit RGB colour space
self._palettes_rgb = np.empty((16, 16, 3), dtype=np.uint8)
# defaultdict(list) mapping palette index to the lines that use this
# palette
self._palette_lines = self._init_palette_lines()
@staticmethod
def _image_colours_cam(image: Image):
colours_rgb = np.asarray(image) # .reshape((-1, 3))
with colour.utilities.suppress_warnings(colour_usage_warnings=True):
colours_cam = colour.convert(colours_rgb, "RGB",
"CAM16UCS").astype(np.float32)
return colours_cam
def _init_palette_lines(self, init_random=False):
palette_lines = defaultdict(list)
if init_random:
lines = list(range(200))
random.shuffle(lines)
idx = 0
while lines:
palette_lines[idx].append(lines.pop())
idx += 1
else:
palette_splits = self._equal_palette_splits()
for i, lh in enumerate(palette_splits):
l, h = lh
palette_lines[i].extend(list(range(l, h)))
return palette_lines
@staticmethod
def _equal_palette_splits(palette_height=35):
# The 16 palettes are striped across consecutive (overlapping) line
# ranges. Since nearby lines tend to have similar colours, this has
# the effect of smoothing out the colour transitions across palettes.
# If we want to overlap 16 palettes in 200 lines, where each palette
# has height H and overlaps the previous one by L lines, then the
# boundaries are at lines:
# (0, H), (H-L, 2H-L), (2H-2L, 3H-2L), ..., (15H-15L, 16H - 15L)
# i.e. 16H - 15L = 200, so for a given palette height H we need to
# overlap by:
# L = (16H - 200)/15
palette_overlap = (16 * palette_height - 200) / 15
palette_ranges = []
for palette_idx in range(16):
palette_lower = palette_idx * (palette_height - palette_overlap)
palette_upper = palette_lower + palette_height
palette_ranges.append((int(np.round(palette_lower)),
int(np.round(palette_upper))))
return palette_ranges
def _perfect_dither(self, source_image: np.ndarray):
"""Dither a "perfect" image using the full 12-bit //gs RGB colour
palette, ignoring restrictions."""
# Suppress divide by zero warning,
# https://github.com/colour-science/colour/issues/900
with colour.utilities.suppress_warnings(python_warnings=True):
full_palette_linear_rgb = colour.convert(
self._rgb12_iigs_to_cam16ucs, "CAM16UCS", "RGB").astype(
np.float32)
total_image_error, image_rgb = dither_shr_pyx.dither_shr_perfect(
source_image, self._rgb12_iigs_to_cam16ucs, full_palette_linear_rgb,
self._rgb24_to_cam16ucs)
# print("Perfect image error:", total_image_error)
return image_rgb
def _dither_image(self, palettes_cam):
# Suppress divide by zero warning,
# https://github.com/colour-science/colour/issues/900
with colour.utilities.suppress_warnings(python_warnings=True):
palettes_linear_rgb = colour.convert(
palettes_cam, "CAM16UCS", "RGB").astype(np.float32)
output_4bit, line_to_palette, total_image_error, palette_line_errors = \
dither_shr_pyx.dither_shr(
self._image_rgb, palettes_cam, palettes_linear_rgb,
self._rgb24_to_cam16ucs)
# Update map of palettes to image lines for which the palette was the
# best match
palette_lines = defaultdict(list)
for line, palette in enumerate(line_to_palette):
palette_lines[palette].append(line)
self._palette_lines = palette_lines
self._palette_line_errors = palette_line_errors
return (output_4bit, line_to_palette, palettes_linear_rgb,
total_image_error)
def iterate(self, max_inner_iterations: int,
max_outer_iterations: int):
total_image_error = 1e9
outer_iterations_since_improvement = 0
while outer_iterations_since_improvement < max_outer_iterations:
inner_iterations_since_improvement = 0
self._palette_lines = self._init_palette_lines()
while inner_iterations_since_improvement < max_inner_iterations:
# print("Iterations %d" % inner_iterations_since_improvement)
new_palettes_cam, new_palettes_rgb12_iigs = (
self._fit_shr_palettes())
# Recompute image with proposed palettes and check whether it
# has lower total image error than our previous best.
(output_4bit, line_to_palette, palettes_linear_rgb,
new_total_image_error) = self._dither_image(new_palettes_cam)
self._reassign_unused_palettes(
line_to_palette, new_palettes_rgb12_iigs)
if new_total_image_error >= total_image_error:
inner_iterations_since_improvement += 1
continue
# We found a globally better set of palettes, so restart the
# clocks
inner_iterations_since_improvement = 0
outer_iterations_since_improvement = -1
total_image_error = new_total_image_error
self._palettes_cam = new_palettes_cam
self._palettes_rgb = new_palettes_rgb12_iigs
yield (new_total_image_error, output_4bit, line_to_palette,
new_palettes_rgb12_iigs, palettes_linear_rgb)
outer_iterations_since_improvement += 1
def _fit_shr_palettes(self) -> Tuple[np.ndarray, np.ndarray]:
"""Attempt to find new palettes that locally improve image quality.
Re-fit a set of 16 palettes from (overlapping) line ranges of the
source image, using k-means clustering in CAM16-UCS colour space.
We maintain the total image error for the pixels on which the 16
palettes are clustered. A new palette that increases this local
image error is rejected.
New palettes that reduce local error cannot be applied immediately
though, because they may cause an increase in *global* image error
when dithering. i.e. they would reduce the overall image quality.
The current (locally) best palettes are returned and can be applied
using accept_palettes()
XXX update
"""
new_palettes_cam = np.empty_like(self._palettes_cam)
new_palettes_rgb12_iigs = np.empty_like(self._palettes_rgb)
# Compute a new 16-colour global palette for the entire image,
# used as the starting center positions for k-means clustering of the
# individual palettes
self._fit_global_palette()
for palette_idx in range(16):
palette_pixels = (
self._colours_cam[self._palette_lines[
palette_idx], :, :].reshape(-1, 3))
# Fix reserved colours from the global palette.
initial_centroids = np.copy(self._global_palette)
pixels_rgb_iigs = dither_shr_pyx.convert_cam16ucs_to_rgb12_iigs(
palette_pixels)
seen_colours = set()
for i in range(self._fixed_colours):
seen_colours.add(tuple(initial_centroids[i, :]))
# Pick unique random colours from the sample points for the
# remaining initial centroids.
for i in range(self._fixed_colours, 16):
choice = np.random.randint(0, pixels_rgb_iigs.shape[0])
new_colour = pixels_rgb_iigs[choice, :]
if tuple(new_colour) in seen_colours:
continue
seen_colours.add(tuple(new_colour))
initial_centroids[i, :] = new_colour
# If there are any single colours in our source //gs RGB pixels that
# represent more than fixed_colour_fraction_threshold of the total,
# then fix these colours for the palette instead of clustering
# them. This reduces artifacting on blocks of colour.
fixed_colour_fraction_threshold = 0.1
most_frequent_colours = sorted(list(zip(
*np.unique(pixels_rgb_iigs, return_counts=True, axis=0))),
key=lambda kv: kv[1], reverse=True)
fixed_colours = self._fixed_colours
for palette_colour, freq in most_frequent_colours:
if (freq < (palette_pixels.shape[0] *
fixed_colour_fraction_threshold)) or (
fixed_colours == 16):
break
if tuple(palette_colour) not in seen_colours:
seen_colours.add(tuple(palette_colour))
initial_centroids[fixed_colours, :] = palette_colour
fixed_colours += 1
palette_rgb12_iigs = dither_shr_pyx.k_means_with_fixed_centroids(
n_clusters=16, n_fixed=fixed_colours,
samples=palette_pixels,
initial_centroids=initial_centroids,
max_iterations=1000,
rgb12_iigs_to_cam16ucs=self._rgb12_iigs_to_cam16ucs)
# If the k-means clustering returned fewer than 16 unique colours,
# fill out the remainder with the most common pixels colours that
# have not yet been used.
#
# TODO: this seems like an opportunity to do something better -
# e.g. forcibly split clusters and iterate the clustering
palette_rgb12_iigs = self._fill_short_palette(
palette_rgb12_iigs, most_frequent_colours)
for i in range(16):
new_palettes_cam[palette_idx, i, :] = (
np.array(dither_shr_pyx.convert_rgb12_iigs_to_cam(
self._rgb12_iigs_to_cam16ucs, palette_rgb12_iigs[
i]), dtype=np.float32))
new_palettes_rgb12_iigs[palette_idx, :, :] = palette_rgb12_iigs
self._palettes_accepted = False
return new_palettes_cam, new_palettes_rgb12_iigs
def _fit_global_palette(self):
"""Compute a 16-colour palette for the entire image to use as
starting point for the sub-palettes. This should help when the image
has large blocks of colour since the sub-palettes will tend to pick the
same colours."""
clusters = cluster.MiniBatchKMeans(n_clusters=16, max_iter=10000)
clusters.fit_predict(self._colours_cam.reshape(-1, 3))
# Dict of {palette idx : frequency count}
palette_freq = {idx: 0 for idx in range(16)}
for idx, freq in zip(*np.unique(clusters.labels_, return_counts=True)):
palette_freq[idx] = freq
frequency_order = [
k for k, v in sorted(
list(palette_freq.items()), key=lambda kv: kv[1], reverse=True)]
self._global_palette = (
dither_shr_pyx.convert_cam16ucs_to_rgb12_iigs(
clusters.cluster_centers_[frequency_order].astype(
np.float32)))
@staticmethod
def _fill_short_palette(palette_iigs_rgb, most_frequent_colours):
"""Fill out the palette to 16 unique entries."""
# We want to maintain order of insertion so that we respect the
# ordering of fixed colours in the palette. Python doesn't have an
# orderedset but dicts preserve insertion order.
palette_set = {}
for palette_entry in palette_iigs_rgb:
palette_set[tuple(palette_entry)] = True
if len(palette_set) == 16:
return palette_iigs_rgb
# Add most frequent image colours that are not yet in the palette
for palette_colour, freq in most_frequent_colours:
if tuple(palette_colour) in palette_set:
continue
palette_set[tuple(palette_colour)] = True
if len(palette_set) == 16:
break
# We couldn't find any more unique colours, fill out with random ones.
while len(palette_set) < 16:
palette_set[
tuple(np.random.randint(0, 16, size=3, dtype=np.uint8))] = True
return np.array(tuple(palette_set.keys()), dtype=np.uint8)
def _reassign_unused_palettes(self, line_to_palette, palettes_iigs_rgb):
palettes_used = [False] * 16
for palette in line_to_palette:
palettes_used[palette] = True
best_palette_lines = [v for k, v in sorted(list(zip(
self._palette_line_errors, range(200))))]
all_palettes = set()
for palette_idx, palette_iigs_rgb in enumerate(palettes_iigs_rgb):
palette_set = set()
for palette_entry in palette_iigs_rgb:
palette_set.add(tuple(palette_entry))
palette_set = frozenset(palette_set)
if palette_set in all_palettes:
print("Duplicate palette", palette_idx, palette_set)
palettes_used[palette_idx] = False
for palette_idx, palette_used in enumerate(palettes_used):
if palette_used:
continue
# TODO: also remove from old entry
worst_line = best_palette_lines.pop()
self._palette_lines[palette_idx] = [worst_line]
def convert(screen, rgb: np.ndarray, args):
# Conversion matrix from RGB to CAM16UCS colour values. Indexed by
# 24-bit RGB value
base_dir = os.path.dirname(__file__)
rgb24_to_cam16ucs = np.load(
os.path.join(base_dir, "data/rgb24_to_cam16ucs.npy"))
rgb12_iigs_to_cam16ucs = np.load(
os.path.join(base_dir, "data/rgb12_iigs_to_cam16ucs.npy"))
# TODO: flags
inner_iterations = 10
outer_iterations = 20
if args.show_output:
pygame.init()
canvas = pygame.display.set_mode((640, 400))
canvas.fill((0, 0, 0))
pygame.display.set_caption("][-Pix image preview")
pygame.event.pump() # Update caption
pygame.display.flip()
total_image_error = None
cluster_palette = ClusterPalette(
rgb, fixed_colours=args.fixed_colours,
rgb12_iigs_to_cam16ucs=rgb12_iigs_to_cam16ucs,
rgb24_to_cam16ucs=rgb24_to_cam16ucs)
output_base, output_ext = os.path.splitext(args.output)
seq = 0
for (
new_total_image_error, output_4bit, line_to_palette,
palettes_rgb12_iigs,
palettes_linear_rgb
) in cluster_palette.iterate(inner_iterations, outer_iterations):
if args.verbose and total_image_error is not None:
print("Improved quality +%f%% (%f)" % (
(1 - new_total_image_error / total_image_error) * 100,
new_total_image_error))
total_image_error = new_total_image_error
for i in range(16):
screen.set_palette(i, palettes_rgb12_iigs[i, :, :])
# Recompute current screen RGB image
screen.set_pixels(output_4bit)
output_rgb = np.empty((200, 320, 3), dtype=np.uint8)
for i in range(200):
screen.line_palette[i] = line_to_palette[i]
output_rgb[i, :, :] = (
palettes_linear_rgb[line_to_palette[i]][
output_4bit[i, :]] * 255
).astype(np.uint8)
output_srgb = (image_py.linear_to_srgb(output_rgb)).astype(np.uint8)
out_image = image_py.resize(
Image.fromarray(output_srgb), screen.X_RES * 2, screen.Y_RES * 2,
srgb_output=True)
if args.show_output:
surface = pygame.surfarray.make_surface(
np.asarray(out_image).transpose((1, 0, 2))) # flip y/x axes
canvas.blit(surface, (0, 0))
pygame.display.set_caption("][-Pix image preview [Iteration %d]"
% seq)
pygame.event.pump() # Update caption
pygame.display.flip()
unique_colours = np.unique(
palettes_rgb12_iigs.reshape(-1, 3), axis=0).shape[0]
if args.verbose:
print("%d unique colours" % unique_colours)
if args.save_preview:
# Save super hi-res image
if args.save_intermediate:
outfile = "%s-%d-preview.png" % (output_base, seq)
else:
outfile = "%s-preview.png" % output_base
out_image.save(outfile, "PNG")
screen.pack()
if args.save_intermediate:
outfile = "%s-%d%s" % (output_base, seq, output_ext)
else:
outfile = "%s%s" % (output_base, output_ext)
with open(outfile, "wb") as f:
f.write(bytes(screen.memory))
seq += 1
if args.show_final_score:
print("FINAL_SCORE:", total_image_error)

View File

@ -1,10 +1,14 @@
# cython: infer_types=True
# cython: profile=False
# cython: boundscheck=False
# cython: wraparound=False
cimport cython
import numpy as np
from libc.stdlib cimport malloc, free
cimport common
# TODO: use a cdef class
# C representation of dither_pattern.DitherPattern data, for efficient access.
@ -17,10 +21,6 @@ cdef struct Dither:
int y_origin
cdef float clip(float a, float min_value, float max_value) nogil:
return min(max(a, min_value), max_value)
# Compute left-hand bounding box for dithering at horizontal position x.
cdef int dither_bounds_xl(Dither *dither, int x) nogil:
cdef int el = max(dither.x_origin - x, 0)
@ -90,8 +90,6 @@ cdef inline unsigned char shift_pixel_window(
#
# Returns: index from 0 .. 2**lookahead into options_nbit representing best available choice for position (x,y)
#
@cython.boundscheck(False)
@cython.wraparound(False)
cdef int dither_lookahead(Dither* dither, float[:, :, ::1] palette_cam16, float[:, :, ::1] palette_rgb,
float[:, :, ::1] image_rgb, int x, int y, int lookahead, unsigned char last_pixels,
int x_res, float[:,::1] rgb_to_cam16ucs, unsigned char palette_depth) nogil:
@ -140,10 +138,10 @@ cdef int dither_lookahead(Dither* dither, float[:, :, ::1] palette_cam16, float[
quant_error[j] = lah_image_rgb[i * lah_shape2 + j] - palette_rgb[next_pixels, phase, j]
apply_one_line(dither, xl, xr, i, lah_image_rgb, lah_shape2, quant_error)
lah_cam16ucs = convert_rgb_to_cam16ucs(
lah_cam16ucs = common.convert_rgb_to_cam16ucs(
rgb_to_cam16ucs, lah_image_rgb[i*lah_shape2], lah_image_rgb[i*lah_shape2+1],
lah_image_rgb[i*lah_shape2+2])
total_error += colour_distance_squared(lah_cam16ucs, palette_cam16[next_pixels, phase])
total_error += common.colour_distance_squared(lah_cam16ucs, palette_cam16[next_pixels, phase])
if total_error >= best_error:
# No need to continue
@ -157,19 +155,6 @@ cdef int dither_lookahead(Dither* dither, float[:, :, ::1] palette_cam16, float[
return best
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline float[::1] convert_rgb_to_cam16ucs(float[:, ::1] rgb_to_cam16ucs, float r, float g, float b) nogil:
cdef int rgb_24bit = (<int>(r*255) << 16) + (<int>(g*255) << 8) + <int>(b*255)
return rgb_to_cam16ucs[rgb_24bit]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline float colour_distance_squared(float[::1] colour1, float[::1] colour2) nogil:
return (colour1[0] - colour2[0]) ** 2 + (colour1[1] - colour2[1]) ** 2 + (colour1[2] - colour2[2]) ** 2
# Perform error diffusion to a single image row.
#
# Args:
@ -190,7 +175,7 @@ cdef void apply_one_line(Dither* dither, int xl, int xr, int x, float[] image, i
for i in range(xl, xr):
error_fraction = dither.pattern[i - x + dither.x_origin]
for j in range(3):
image[i * image_shape1 + j] = clip(image[i * image_shape1 + j] + error_fraction * quant_error[j], 0, 1)
image[i * image_shape1 + j] = common.clip(image[i * image_shape1 + j] + error_fraction * quant_error[j], 0, 1)
# Perform error diffusion across multiple image rows.
@ -204,8 +189,6 @@ cdef void apply_one_line(Dither* dither, int xl, int xr, int x, float[] image, i
# image: RGB pixel data, to be mutated
# quant_error: RGB quantization error to be diffused
#
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void apply(Dither* dither, int x_res, int y_res, int x, int y, float[:,:,::1] image, float[] quant_error) nogil:
cdef int i, j, k
@ -220,11 +203,9 @@ cdef void apply(Dither* dither, int x_res, int y_res, int x, int y, float[:,:,::
for j in range(xl, xr):
error_fraction = dither.pattern[(i - y) * dither.x_shape + j - x + dither.x_origin]
for k in range(3):
image[i,j,k] = clip(image[i,j,k] + error_fraction * quant_error[k], 0, 1)
image[i,j,k] = common.clip(image[i,j,k] + error_fraction * quant_error[k], 0, 1)
@cython.boundscheck(False)
@cython.wraparound(False)
cdef image_nbit_to_bitmap(
(unsigned char)[:, ::1] image_nbit, unsigned int x_res, unsigned int y_res, unsigned char palette_depth):
cdef unsigned int x, y
@ -247,8 +228,6 @@ cdef image_nbit_to_bitmap(
#
# Returns: tuple of n-bit output image array and RGB output image array
#
@cython.boundscheck(False)
@cython.wraparound(False)
def dither_image(
screen, float[:, :, ::1] image_rgb, dither, int lookahead, unsigned char verbose, float[:,::1] rgb_to_cam16ucs):
cdef int y, x

400
dither_shr.pyx Normal file
View File

@ -0,0 +1,400 @@
# cython: infer_types=True
# cython: profile=False
# cython: boundscheck=False
# cython: wraparound=False
cimport cython
import colour
import numpy as np
cimport common
def dither_shr_perfect(
float[:, :, ::1] input_rgb, float[:, ::1] full_palette_cam, float[:, ::1] full_palette_rgb,
float[:,::1] rgb_to_cam16ucs):
cdef int y, x, idx, best_colour_idx, i
cdef double best_distance, distance, total_image_error
cdef float[::1] best_colour_rgb, pixel_cam
cdef float quant_error
cdef float[:, ::1] palette_rgb, palette_cam
cdef float[:, :, ::1] working_image = np.copy(input_rgb)
cdef float[:, ::1] line_cam = np.zeros((320, 3), dtype=np.float32)
cdef int palette_size = full_palette_rgb.shape[0]
cdef float decay = 0.5
cdef int floyd_steinberg = 1
total_image_error = 0.0
for y in range(200):
for x in range(320):
line_cam[x, :] = common.convert_rgb_to_cam16ucs(
rgb_to_cam16ucs, working_image[y,x,0], working_image[y,x,1], working_image[y,x,2])
for x in range(320):
pixel_cam = common.convert_rgb_to_cam16ucs(
rgb_to_cam16ucs, working_image[y, x, 0], working_image[y, x, 1], working_image[y, x, 2])
best_distance = 1e9
best_colour_idx = -1
for idx in range(palette_size):
distance = common.colour_distance_squared(pixel_cam, full_palette_cam[idx, :])
if distance < best_distance:
best_distance = distance
best_colour_idx = idx
best_colour_rgb = full_palette_rgb[best_colour_idx, :]
total_image_error += best_distance
for i in range(3):
quant_error = working_image[y, x, i] - best_colour_rgb[i]
working_image[y, x, i] = best_colour_rgb[i]
if floyd_steinberg:
# Floyd-Steinberg dither
# 0 * 7
# 3 5 1
if x < 319:
working_image[y, x + 1, i] = common.clip(
working_image[y, x + 1, i] + quant_error * (7 / 16), 0, 1)
if y < 199:
if x > 0:
working_image[y + 1, x - 1, i] = common.clip(
working_image[y + 1, x - 1, i] + decay * quant_error * (3 / 16), 0, 1)
working_image[y + 1, x, i] = common.clip(
working_image[y + 1, x, i] + decay * quant_error * (5 / 16), 0, 1)
if x < 319:
working_image[y + 1, x + 1, i] = common.clip(
working_image[y + 1, x + 1, i] + decay * quant_error * (1 / 16), 0, 1)
else:
# Jarvis
# 0 0 X 7 5
# 3 5 7 5 3
# 1 3 5 3 1
if x < 319:
working_image[y, x + 1, i] = common.clip(
working_image[y, x + 1, i] + quant_error * (7 / 48), 0, 1)
if x < 318:
working_image[y, x + 2, i] = common.clip(
working_image[y, x + 2, i] + quant_error * (5 / 48), 0, 1)
if y < 199:
if x > 1:
working_image[y + 1, x - 2, i] = common.clip(
working_image[y + 1, x - 2, i] + decay * quant_error * (3 / 48), 0,
1)
if x > 0:
working_image[y + 1, x - 1, i] = common.clip(
working_image[y + 1, x - 1, i] + decay * quant_error * (5 / 48), 0,
1)
working_image[y + 1, x, i] = common.clip(
working_image[y + 1, x, i] + decay * quant_error * (7 / 48), 0, 1)
if x < 319:
working_image[y + 1, x + 1, i] = common.clip(
working_image[y + 1, x + 1, i] + decay * quant_error * (5 / 48),
0, 1)
if x < 318:
working_image[y + 1, x + 2, i] = common.clip(
working_image[y + 1, x + 2, i] + decay * quant_error * (3 / 48),
0, 1)
if y < 198:
if x > 1:
working_image[y + 2, x - 2, i] = common.clip(
working_image[y + 2, x - 2, i] + decay * decay * quant_error * (1 / 48), 0,
1)
if x > 0:
working_image[y + 2, x - 1, i] = common.clip(
working_image[y + 2, x - 1, i] + decay * decay * quant_error * (3 / 48), 0,
1)
working_image[y + 2, x, i] = common.clip(
working_image[y + 2, x, i] + decay * decay * quant_error * (5 / 48), 0, 1)
if x < 319:
working_image[y + 2, x + 1, i] = common.clip(
working_image[y + 2, x + 1, i] + decay * decay * quant_error * (3 / 48),
0, 1)
if x < 318:
working_image[y + 2, x + 2, i] = common.clip(
working_image[y + 2, x + 2, i] + decay * decay * quant_error * (1 / 48),
0, 1)
return total_image_error, working_image
def dither_shr(
float[:, :, ::1] input_rgb, float[:, :, ::1] palettes_cam, float[:, :, ::1] palettes_rgb,
float[:,::1] rgb_to_cam16ucs):
cdef int y, x, idx, best_colour_idx, best_palette, i
cdef double best_distance, distance, total_image_error
cdef float[::1] best_colour_rgb, pixel_cam
cdef float quant_error
cdef float[:, ::1] palette_rgb, palette_cam
cdef (unsigned char)[:, ::1] output_4bit = np.zeros((200, 320), dtype=np.uint8)
cdef float[:, :, ::1] working_image = np.copy(input_rgb)
cdef float[:, ::1] line_cam = np.zeros((320, 3), dtype=np.float32)
cdef int[::1] line_to_palette = np.zeros(200, dtype=np.int32)
cdef double[::1] palette_line_errors = np.zeros(200, dtype=np.float64)
cdef PaletteSelection palette_line
cdef float decay = 0.5
cdef int floyd_steinberg = 1
best_palette = -1
total_image_error = 0.0
for y in range(200):
for x in range(320):
line_cam[x, :] = common.convert_rgb_to_cam16ucs(
rgb_to_cam16ucs, working_image[y,x,0], working_image[y,x,1], working_image[y,x,2])
palette_line = best_palette_for_line(line_cam, palettes_cam, best_palette)
best_palette = palette_line.palette_idx
palette_line_errors[y] = palette_line.total_error
palette_rgb = palettes_rgb[best_palette, :, :]
palette_cam = palettes_cam[best_palette, :, :]
line_to_palette[y] = best_palette
for x in range(320):
pixel_cam = common.convert_rgb_to_cam16ucs(
rgb_to_cam16ucs, working_image[y, x, 0], working_image[y, x, 1], working_image[y, x, 2])
best_distance = 1e9
best_colour_idx = -1
for idx in range(16):
distance = common.colour_distance_squared(pixel_cam, palette_cam[idx, :])
if distance < best_distance:
best_distance = distance
best_colour_idx = idx
best_colour_rgb = palette_rgb[best_colour_idx]
output_4bit[y, x] = best_colour_idx
total_image_error += best_distance
for i in range(3):
quant_error = working_image[y, x, i] - best_colour_rgb[i]
working_image[y, x, i] = best_colour_rgb[i]
if floyd_steinberg:
# Floyd-Steinberg dither
# 0 * 7
# 3 5 1
if x < 319:
working_image[y, x + 1, i] = common.clip(
working_image[y, x + 1, i] + quant_error * (7 / 16), 0, 1)
if y < 199:
if x > 0:
working_image[y + 1, x - 1, i] = common.clip(
working_image[y + 1, x - 1, i] + decay * quant_error * (3 / 16), 0, 1)
working_image[y + 1, x, i] = common.clip(
working_image[y + 1, x, i] + decay * quant_error * (5 / 16), 0, 1)
if x < 319:
working_image[y + 1, x + 1, i] = common.clip(
working_image[y + 1, x + 1, i] + decay * quant_error * (1 / 16), 0, 1)
else:
# Jarvis
# 0 0 X 7 5
# 3 5 7 5 3
# 1 3 5 3 1
if x < 319:
working_image[y, x + 1, i] = common.clip(
working_image[y, x + 1, i] + quant_error * (7 / 48), 0, 1)
if x < 318:
working_image[y, x + 2, i] = common.clip(
working_image[y, x + 2, i] + quant_error * (5 / 48), 0, 1)
if y < 199:
if x > 1:
working_image[y + 1, x - 2, i] = common.clip(
working_image[y + 1, x - 2, i] + decay * quant_error * (3 / 48), 0,
1)
if x > 0:
working_image[y + 1, x - 1, i] = common.clip(
working_image[y + 1, x - 1, i] + decay * quant_error * (5 / 48), 0,
1)
working_image[y + 1, x, i] = common.clip(
working_image[y + 1, x, i] + decay * quant_error * (7 / 48), 0, 1)
if x < 319:
working_image[y + 1, x + 1, i] = common.clip(
working_image[y + 1, x + 1, i] + decay * quant_error * (5 / 48),
0, 1)
if x < 318:
working_image[y + 1, x + 2, i] = common.clip(
working_image[y + 1, x + 2, i] + decay * quant_error * (3 / 48),
0, 1)
if y < 198:
if x > 1:
working_image[y + 2, x - 2, i] = common.clip(
working_image[y + 2, x - 2, i] + decay * decay * quant_error * (1 / 48), 0,
1)
if x > 0:
working_image[y + 2, x - 1, i] = common.clip(
working_image[y + 2, x - 1, i] + decay * decay * quant_error * (3 / 48), 0,
1)
working_image[y + 2, x, i] = common.clip(
working_image[y + 2, x, i] + decay * decay * quant_error * (5 / 48), 0, 1)
if x < 319:
working_image[y + 2, x + 1, i] = common.clip(
working_image[y + 2, x + 1, i] + decay * decay * quant_error * (3 / 48),
0, 1)
if x < 318:
working_image[y + 2, x + 2, i] = common.clip(
working_image[y + 2, x + 2, i] + decay * decay * quant_error * (1 / 48),
0, 1)
return (
np.array(output_4bit, dtype=np.uint8), line_to_palette, total_image_error,
np.array(palette_line_errors, dtype=np.float64)
)
cdef struct PaletteSelection:
int palette_idx
double total_error
cdef PaletteSelection best_palette_for_line(
float [:, ::1] line_cam, float[:, :, ::1] palettes_cam, int last_palette_idx) nogil:
cdef int palette_idx, best_palette_idx, palette_entry_idx, pixel_idx
cdef double best_total_dist, total_dist, best_pixel_dist, pixel_dist
cdef float[:, ::1] palette_cam
cdef float[::1] pixel_cam
best_total_dist = 1e9
best_palette_idx = -1
cdef int line_size = line_cam.shape[0]
for palette_idx in range(16):
palette_cam = palettes_cam[palette_idx, :, :]
total_dist = 0
for pixel_idx in range(line_size):
pixel_cam = line_cam[pixel_idx]
best_pixel_dist = 1e9
for palette_entry_idx in range(16):
pixel_dist = common.colour_distance_squared(pixel_cam, palette_cam[palette_entry_idx, :])
if pixel_dist < best_pixel_dist:
best_pixel_dist = pixel_dist
total_dist += best_pixel_dist
if total_dist < best_total_dist:
best_total_dist = total_dist
best_palette_idx = palette_idx
cdef PaletteSelection res
res.palette_idx = best_palette_idx
res.total_error = best_total_dist
return res
cdef float[::1] _convert_rgb12_iigs_to_cam(float [:, ::1] rgb12_iigs_to_cam16ucs, (unsigned char)[::1] point_rgb12) nogil:
cdef int rgb12 = (point_rgb12[0] << 8) | (point_rgb12[1] << 4) | point_rgb12[2]
return rgb12_iigs_to_cam16ucs[rgb12]
# Wrapper around _convert_rgb12_iigs_to_cam to allow calling from python while retaining fast path for cython calls.
def convert_rgb12_iigs_to_cam(float [:, ::1] rgb12_iigs_to_cam16ucs, (unsigned char)[::1] point_rgb12) -> float[::1]:
return _convert_rgb12_iigs_to_cam(rgb12_iigs_to_cam16ucs, point_rgb12)
@cython.cdivision(True)
cdef float[:, ::1] linear_to_srgb_array(float[:, ::1] a, float gamma=2.4):
cdef int i, j
cdef float[:, ::1] res = np.empty_like(a, dtype=np.float32)
for i in range(res.shape[0]):
for j in range(3):
if a[i, j] <= 0.0031308:
res[i, j] = a[i, j] * 12.92
else:
res[i, j] = 1.055 * a[i, j] ** (1.0 / gamma) - 0.055
return res
cdef (unsigned char)[:, ::1] _convert_cam16ucs_to_rgb12_iigs(float[:, ::1] point_cam):
cdef float[:, ::1] rgb
cdef (float)[:, ::1] rgb12_iigs
# Convert CAM16UCS input to RGB. Even though this dynamically constructs a path on the graph of colour conversions
# every time, in practise this seems to have a negligible overhead compared to the actual conversion functions.
with colour.utilities.suppress_warnings(python_warnings=True):
rgb = colour.convert(point_cam, "CAM16UCS", "RGB").astype(np.float32)
# TODO: precompute this conversion matrix since it's static. This accounts for about 10% of the CPU time here.
rgb12_iigs = np.clip(
# Convert to Rec.601 R'G'B'
colour.YCbCr_to_RGB(
# Gamma correct and convert Rec.709 R'G'B' to YCbCr
colour.RGB_to_YCbCr(
linear_to_srgb_array(rgb), K=colour.WEIGHTS_YCBCR['ITU-R BT.709']),
K=colour.WEIGHTS_YCBCR['ITU-R BT.601']), 0, 1).astype(np.float32) * 15
return np.round(rgb12_iigs).astype(np.uint8)
# Wrapper around _convert_cam16ucs_to_rgb12_iigs to allow calling from python while retaining fast path for cython
# calls.
def convert_cam16ucs_to_rgb12_iigs(float[:, ::1] point_cam):
return _convert_cam16ucs_to_rgb12_iigs(point_cam)
@cython.cdivision(True)
def k_means_with_fixed_centroids(
int n_clusters, int n_fixed, float[:, ::1] samples, (unsigned char)[:, ::1] initial_centroids, int max_iterations,
float [:, ::1] rgb12_iigs_to_cam16ucs):
cdef double error, best_error, total_error, last_total_error
cdef int centroid_idx, closest_centroid_idx, i, point_idx
cdef (unsigned char)[:, ::1] centroids_rgb12 = np.copy(initial_centroids)
cdef (unsigned char)[:, ::1] new_centroids_rgb12
cdef float[::1] point_cam
cdef float[:, ::1] new_centroids_cam = np.empty((n_clusters - n_fixed, 3), dtype=np.float32)
cdef float[:, ::1] centroid_cam_sample_positions_total
cdef int[::1] centroid_sample_counts
last_total_error = 1e9
for iteration in range(max_iterations):
total_error = 0.0
centroid_cam_sample_positions_total = np.zeros((16, 3), dtype=np.float32)
centroid_sample_counts = np.zeros(16, dtype=np.int32)
# For each sample, associate it to the closest centroid. We want to compute the mean of all associated samples
# but we do this by accumulating the (coordinate vector) total and number of associated samples.
#
# Centroid positions are tracked in 4-bit //gs RGB colour space with distances measured in CAM16UCS colour
# space.
for point_idx in range(samples.shape[0]):
point_cam = samples[point_idx, :]
best_error = 1e9
closest_centroid_idx = 0
for centroid_idx in range(n_clusters):
error = common.colour_distance_squared(
_convert_rgb12_iigs_to_cam(rgb12_iigs_to_cam16ucs, centroids_rgb12[centroid_idx, :]), point_cam)
if error < best_error:
best_error = error
closest_centroid_idx = centroid_idx
for i in range(3):
centroid_cam_sample_positions_total[closest_centroid_idx, i] += point_cam[i]
centroid_sample_counts[closest_centroid_idx] += 1
total_error += best_error
# Since the allowed centroid positions are discrete (and not uniformly spaced in CAM16UCS colour space), we
# can't rely on measuring total centroid movement as a termination condition. e.g. sometimes the nearest
# available point to an intended next centroid position will increase the total distance, or centroids may
# oscillate between two neighbouring positions. Instead, we terminate when the total error stops decreasing.
if total_error >= last_total_error:
break
last_total_error = total_error
# Compute new centroid positions in CAM16UCS colour space
for centroid_idx in range(n_fixed, n_clusters):
if centroid_sample_counts[centroid_idx]:
for i in range(3):
new_centroids_cam[centroid_idx - n_fixed, i] = (
centroid_cam_sample_positions_total[centroid_idx, i] / centroid_sample_counts[centroid_idx])
# Convert all new centroids back to //gb RGB colour space (done as a single matrix since
# _convert_cam16ucs_to_rgb12_iigs has nontrivial overhead)
new_centroids_rgb12 = _convert_cam16ucs_to_rgb12_iigs(new_centroids_cam)
# Update positions for non-fixed centroids
for centroid_idx in range(n_clusters - n_fixed):
for i in range(3):
if centroids_rgb12[centroid_idx + n_fixed, i] != new_centroids_rgb12[centroid_idx, i]:
centroids_rgb12[centroid_idx + n_fixed, i] = new_centroids_rgb12[centroid_idx, i]
return centroids_rgb12

266
docs/dhr.md Normal file
View File

@ -0,0 +1,266 @@
# Double Hi-Res image conversion
## Some background on Apple II Double Hi-Res graphics
Like other (pre-//gs) Apple II graphics modes, Double Hi-Res relies on [NTSC Artifact Colour](https://en.wikipedia.org/wiki/Composite_artifact_colors), which means that the colour of a pixel is entirely determined by its horizontal position on the screen, and the on/off status of preceding horizontal pixels.
In Double Hi-Res mode, the 560 horizontal pixels per line are individually addressable. This is an improvement over the (single) Hi-Res mode, which also has 560 horizontal pixels, but which can only be addressed in groups of two (with an option to shift blocks of 7 pixels each by one dot). See _Assembly Lines: The Complete Book_ (Wagner) for a detailed introduction to this, or _Understanding the Apple IIe_ (Sather) for a deep technical discussion.
Double Hi-Res is usually characterized as being capable of producing 16 display colours, but with heavy restrictions on how these colours can be arranged horizontally.
### Naive model: 140x192x16
One simple model for Double Hi-Res graphics is to only treat the display in groups of 4 horizontal pixels, which gives an effective resolution of 140x192 in 16 colours (=2^4). These 140 pixel colours can be chosen independently, which makes this model easy to think about and to work with (e.g. when creating images by hand). However the resulting images will exhibit (sometimes severe) colour interference/fringing effects when two colours are next to one another, because the underlying hardware does not actually work this way. See below for an example image conversion, showing the unwanted colour fringing that results.
### Simplest realistic model: 560 pixels, 4-pixel colour
A more complete model for thinking about DHGR comes from looking at how the NTSC signal produces colour on the display.
The [NTSC chrominance subcarrier](https://en.wikipedia.org/wiki/Chrominance_subcarrier) completes one complete phase cycle in the time taken to draw 4 horizontal dots. The colours produced are due to the interactions of the pixel luminosity (on/off) relative to this NTSC chroma phase.
What this means is that the colour of each of the 560 horizontal pixels is determined by the current pixel value (on/off), the current X-coordinate modulo 4 (X coordinate relative to NTSC phase), as well as the on-off status of the pixels to the left of it.
The simplest approximation is to only look at the current pixel value and the 3 pixels to the left, i.e. to consider a sliding window of 4 horizontal pixels moving across the screen from left to right. Within this window, we have one pixel for each of the 4 values of NTSC phase (x % 4, ranging from 0 .. 3). The on-off values for these 4 values of NTSC phase determine the colour of the pixel. See [here](https://docs.google.com/presentation/d/1_eqBknG-4-llQw3oAOmPO3FlawUeWCeRPYpr_mh2iRU/edit) for more details.
This model allows us to understand and predict the interference behaviour when two "140px" colours are next to each other, and to go beyond this "140px" model to take more advantage of the true 560px horizontal resolution.
If we imagine drawing pixels from left to right across the screen, at each pixel we only have *two* accessible choices of colour: those resulting from turning the current pixel on, or off. Which two particular colours are produced are determined by the pixels already drawn to the left (the immediate 3 neighbours, in our model). One of these possibilities will always be the same as the pixel colour to the left (the on/off pixel choice corresponding to the value that just "fell off the left side" of the sliding window), and the other choice is some other colour from our palette of 16.
This can be summarized in a chart, showing the possible colour transitions depending on the colour of the pixel to the immediate left, and the value of x%4.
![Double hi-res colour transitions](Double_Hi-Res_colour_transitions.png)
So, if we want to transition from one colour to a particular new colour, it may take up to 4 horizontal pixels before we are able to achieve it (e.g. transitioning all the way from black (0000) to white (1111)). In the meantime we have to transition through up to 2 other colours. Depending on the details of the image we are aiming for, this may either produce unwanted visual noise, or can actually be beneficial (e.g. if the colour we want is available immediately at the next pixel)
These constraints are difficult to work with when constructing DHGR graphics "by hand", but we can account for them programmatically in our image conversion to take full advantage of the "true" 560px resolution while accounting for colour interference effects.
#### Limitations of this colour model
In practise the above description of the Apple II colour model is still only an approximation. On real hardware, the video signal is a continuous analogue signal, and colour is continuously modulated rather than producing discretely-coloured pixels with fixed colour values.
More importantly, in an NTSC video signal the colour (chroma) signal has a lower bandwidth than the luma (brightness) signal ([Chroma sub-sampling](https://en.wikipedia.org/wiki/Chroma_subsampling)), which means that colours will tend to bleed across more than 4 pixels. However our simple "4-pixel chroma bleed" model already produces good results, and exactly matches the implementation behaviour of some emulators, e.g. Virtual II.
### NTSC emulation and 8-pixel colour
By simulating the NTSC (Y'UV) signal directly we are able to recover the Apple II colour output from "first principles". Here are the 16 "basic" DHGR colours, obtained using saturation/hue parameters tuned to match OpenEmulator's NTSC implementation, and allowing chroma to bleed across 4 pixels.
![NTSC colours with 4 pixel chroma bleed](ntsc-colours-chroma-bleed-4.png)
However in real NTSC, chroma bleeds over more than 4 pixels, which means that we actually have more than 2^4 colours available to work with.
This means that **when viewed on a composite colour display, Double Hi-Res graphics is not just a 16-colour graphics mode!**
If we allow the NTSC chroma signal to bleed over 8 pixels instead of 4, then the resulting colour is determined by sequences of 8 pixels instead of 4 pixels, i.e. there are 2^8 = 256 possibilities. In practise many of these result in the same output colour, and (with this approximation) there are only 85 unique colours available. However this is still a marked improvement on the 16 "basic" DHGR colours:
![NTSC colours with 8 pixel chroma bleed](ntsc-colours-chroma-bleed-8.png)
The "extra" DHGR colours are only available on real hardware, or an emulator that implements NTSC chroma sub-sampling (such as OpenEmulator). But the result is that on such targets a much larger range of colours is available for use in image conversion. However the restriction still exists that any given pixel only has a choice of 2 colours available (as determined by the on/off state of pixels to the left).
In practise this gives much better image quality, especially when shading areas of similar colour. The Apple II is still unable to directly modulate the luma (brightness) NTSC signal component, so areas of low or high brightness still tend to be heavily dithered. This is because there are more bit sequences that have the number of '1' bits close to the average than there are at the extremes, so there are correspondingly few available colours that are very bright or very dark.
These 85 unique double hi-res colours produced by the ][-pix NTSC emulation are not the definitive story - though they're closer to it than the usual story that double hi-res is a 16-colour graphics mode. The implementation used by ][-pix is the simplest one: the Y'UV signal is averaged with a sliding window of 4 pixels for the Y' (luma) component and 8 pixels for the UV (chroma) component.
The choice of 8 pixels is not strictly correct - e.g. the chroma bandwidth (~0.6MHz) is much less than half of luma bandwidth (~2Mhz) so the signal bleeds over more than twice as many pixels; but also decays in a more complex way than the simple step function sliding window chosen here. In practise using 8 pixels is a good compromise between ease of implementation, runtime performance and fidelity.
By contrast, OpenEmulator uses a more complex (and realistic) band-pass filtering to produce its colour output, which presumably allows even more possible colours (physical hardware will also produce its own unique results, depending on the hardware implementation of the signal decoding, and other physical characteristics). I expect that most of these will be small variations on the above though; and in practise the ][-pix NTSC implementation already produces a close colour match for the OpenEmulator behaviour.
#### Examples of NTSC images
(Source: [Reinhold Möller](https://commons.wikimedia.org/wiki/File:Nymphaea_caerulea-20091014-RM-115245.jpg), [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0), via Wikimedia Commons)
![Nymphaea](../examples/nymphaea-original.png)
OpenEmulator screenshot of image produced with `--palette=openemulator --lookahead=8`. The distorted background colour compared to the original is particularly noticeable.
![Nymphaea](../examples/nymphaea-iipix-openemulator-openemulator.png)
OpenEmulator screenshot of image produced with `--palette=ntsc --lookahead=8`. Not only is the background colour a much better match, the image shading and detail is markedly improved.
![Nymphaea](../examples/nymphaea-iipix-ntsc-openemulator.png)
Rendering the same .dhr image with 4-pixel colour shows the reason for the difference. For example the background shading is due to pixel sequences that appear (with this simpler and less hardware-accurate rendering scheme) as sequences of grey and dark green, with a lot of blue and red sprinkled in. In NTSC these pixel sequences combine to produce various shades of green.
![Nymphaea](../examples/nymphaea-iipix-ntsc-preview-openemulator.png)
# Dithering and Double Hi-Res
[Dithering](https://en.wikipedia.org/wiki/Dither) an image to produce an approximation with fewer image colours is a well-known technique. The basic idea is to pick a "best colour match" for a pixel from our limited palette, then to compute the difference between the true and selected colour values and diffuse this error to nearby pixels (using some pattern).
In the particular case of DHGR this algorithm runs into difficulties, because each pixel only has two possible colour choices (from a total of 16+). If we only consider the two possibilities for the immediate next pixel then neither may be a particularly good match. However it may be more beneficial to make a suboptimal choice now (deliberately introduce more error), if it allows us access to a better colour for a subsequent pixel. "Classical" dithering algorithms do not account for these palette constraints, and produce suboptimal image quality for DHGR conversions.
We can deal with this by looking ahead N pixels (8 by default) for each image position (x,y), and computing the effect of choosing all 2^N combinations of these N-pixel states on the dithered source image.
Specifically, for a fixed choice of one of these N pixel sequences, we tentatively perform the error diffusion as normal on a copy of the image, and compute the total mean squared distance from the (fixed) N-pixel sequence to the error-diffused source image. To compute the perceptual difference between colours we convert to the perceptually uniform [CAM16-UCS](https://en.wikipedia.org/wiki/Color_appearance_model#CAM16) colour space in which perceptual distance is Euclidean.
Finally, we pick the N-pixel sequence with the lowest total error, and select the first pixel of this N-pixel sequence for position (x,y). We then perform error diffusion as usual for this single pixel, and proceed to x+1.
This allows us to "look beyond" local minima to find cases where it is better to make a suboptimal choice now to allow better overall image quality in subsequent pixels. Since we will sometimes find that our choice of 2 next-pixel colours actually includes (or comes close to) the "ideal" choice, this means we can take maximal advantage of the 560-pixel horizontal resolution.
## Gamma correction
Most digital images are encoded using the [sRGB colour space](https://en.wikipedia.org/wiki/SRGB), which means that the stored RGB values do not map linearly onto the rendered colour intensities. In order to work with linearized RGB values the source image needs to be gamma corrected. Otherwise, the process of dithering an un-gamma-corrected image tends to result in an output that does not match the brightness of the input. In particular shadows and highlights tend to get blown out/over-exposed.
## Dither pattern
The process of (error-diffusion) dithering involves distributing the "quantization error" (mismatch between the colour of the source image and chosen output pixels) across neighbouring pixels, according to some pattern. [Floyd-Steinberg](https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering) and [Jarvis-Judice-Ninke](https://en.wikipedia.org/wiki/Error_diffusion#minimized_average_error) ("Jarvis") are two common patterns, though there are many others, which have slightly different characteristics.
Since it uses a small dither pattern, Floyd-Steinberg dithering retains more of the image detail than larger kernels. On the other hand, it sometimes produces image artifacts that are highly structured (e.g. runs of a single colour, checkerboard patterns). This seems to be especially common with 4-pixel colours.
In part this may be because these "classical" dither patterns only propagate errors to a small number of neighbouring pixels, e.g. 1 pixels in the forward direction for Floyd-Steinberg, and 2 pixels for Jarvis. However for double hi-res colours we know that it might take up to 4 pixels before a given colour can be selected for output (e.g. to alternate between black and white, or any other pairs that are 4 steps away on the transition chart above).
In other words, given the results of error diffusion from our current pixel, there is one colour from our palette of 16 that is the best one to match this - but it might be only possible to render this particular colour up to 4 pixels further on. If we only diffuse the errors by 1 or 2 pixels each time, it will tend to have diffused away by the time we reach that position, and the opportunity will be lost. Combined with the small overall set of available colours this can result in image artifacts.
Modifying the Jarvis dither pattern to extend 4 pixels in the forward direction seems to give much better results for such images (e.g. when dithering large blocks of colour), although at the cost of reduced detail. This is presumably because we allow each quantization error to diffuse to each of the 4 subsequent pixels that might be best-placed to act on it.
The bottom line is that choice of `--dither` argument is a tradeoff between image detail and handling of colour. If the default `--dither=floyd` algorithm does not give pleasing results, try other patterns such as `--dither=jarvis-mod`.
Further experimentation with other dithering patterns (and similar modifications to the above) may also produce interesting results.
## Palettes
Since the Apple II graphics (prior to //gs) are not based on RGB colour, we have to choose an (approximate) RGB colour palette when dithering an RGB image. There is no "true" choice for this palette, since it depends heavily on how the image is viewed:
1. Different emulators have made (often quite different) choices for the RGB colour palettes used to emulate Apple II graphics on a RGB display. This means that an image that looks good on one emulator may not look good on another (or on real hardware).
- For example, Virtual II (and the Apple //gs) uses two different RGB shades of grey for the two DHGR grey colours, whereas they are rendered identically in NTSC. That means that images not targeted for the Virtual II palette will look quite different when viewed there (and vice versa).
2. Secondly, the actual display colours rendered by an Apple II are not fixed, but bleed into each other due to the behaviour of the (analogue) NTSC video signal. i.e. the entire notion of a "16-colour RGB palette" is a flawed one. Furthermore, the NTSC colours depend on the particular monitor/TV and its tuning (brightness/contrast/hue settings etc). "Never Twice the Same Colour" indeed. The "4-pixel colour" model described above where we can assign 2 from 16 fixed colours to each of 560 discrete pixels is only an approximation (though a useful one in practise).
Some emulators emulate the NTSC video signal more faithfully (e.g. OpenEmulator), in which case they do not have a true "RGB palette". The best we can do here is measure the colours that are produced by large blocks of colour, i.e. where there is no colour blending. Others use some discrete approximation (e.g. Virtual II seems to exactly match the colour model described above), so a fixed palette can be reconstructed.
To compute the emulator palettes used by ][-pix I measured the sRGB colour values produced by a full-screen Apple II colour image (using the colour picker tool of Mac OS X), using default emulator settings. I have not yet attempted to measure/estimate palettes of other emulators, or "real hardware"
Existing conversion tools (see below) tend to support a variety of RGB palette values sourced from various places (older tools, emulators, theoretical estimations etc). In practise, these only matter in a few ways:
1. If you are trying to target colour balance as accurately as possible for a particular viewing target (e.g. emulator), i.e. so that the rendered colour output looks as close as possible to the source image.
2. If you are targeting an emulator that has a "non-standard" colour model, e.g. Virtual II with its two distinct shades of grey.
3. Otherwise, choices of palette effectively amount to changing the colour balance of the source image. Some of these might produce better image quality for a particular image (e.g. if the source image contains large colour blocks that are difficult to approximate with a particular target palette), at the cost of changing the colour balance. i.e. it might look good on its own but not match the source image. You could also achieve similar results by tweaking the colour balance of the source image in an editor, e.g GIMP or Photoshop.
## Precomputing distance matrix
The mapping from RGB colour space to CAM16-UCS is quite complex, so to avoid this runtime cost we precompute a matrix from all 256^3 integer RGB values to corresponding CAM16-UCS values. This 192MB matrix is generated by the `precompute_conversion.py` utility, and is loaded at runtime for efficient access.
# Comparison to other DHGR image converters
## bmp2dhr
* [bmp2dhr](http://www.appleoldies.ca/bmp2dhr/) (see [here](https://github.com/digarok/b2d) for a maintained code fork) supports additional graphics modes not yet supported by ][-pix, namely (double) lo-res, and hi-res. Support for the lores modes would be easy to add to ][-pix, although hi-res requires more work to accommodate the colour model. A similar lookahead strategy will likely work well though.
* supports additional image dither modes
* only supports BMP source images in a particular format.
* DHGR conversions are treated as simple 140x192x16 colour images without colour constraints, and ignores the colour fringing behaviour described above. The generated .bmp preview images also do not show fringing, but it is present when viewing the image on an Apple II or emulator that accounts for it. i.e. the preview images are sometimes not very representative of the actual results. See below for an example.
* Apart from ignoring DHGR colour interactions, the 140px converted images are also lower than ideal resolution since they do not make use of the ability to address all 560px independently.
* The perceptual colour distance metric used to match the best colour to an input pixel is a custom metric based on a weighted sum of Euclidean sRGB distance and Rec.601 luma value. It's not explained why this particular metric was chosen, and in practise it seems to often give much lower quality results than modern perceptually uniform colour spaces like CIE2000 or CAM16-UCS (though these are much slower to compute - which is why we precompute the conversion matrix ahead of time)
* It does not perform RGB colour space conversions before dithering, i.e. if the input image is in sRGB colour space (as most digital images will be) then the dithering is also performed in sRGB. Since sRGB is not a linear colour space, the effect of dithering is to distribute errors non-linearly, which distorts the brightness of the resulting image.
## a2bestpix
* Like ][-pix, [a2bestpix](http://lukazi.blogspot.com/2017/03/double-high-resolution-graphics-dhgr.html) only supports DHGR conversion. Overall quality is usually fairly good, although colours and brightness are slightly distorted (for reasons described below), and the generated preview images do not quite give a faithful representation of the native image rendering.
* Like ][-pix, and unlike bmp2dhr, a2bestpix does apply a model of the DHGR colour interactions, albeit an ad-hoc one based on rules and tables of 4-pixel "colour blocks" reconstructed from (AppleWin) emulator behaviour. This does allow it to make use of (closer to) full 560px resolution, although it still treats the screen as a sequence of 140 4-pixel colour blocks (with some constraints on the allowed arrangement of these blocks).
* supports additional (custom) dither modes (partly out of necessity due to the custom "colour block" model)
* Supports a variety of perceptual colour distance metrics including CIE2000 and the one bmp2dhr uses. In practise I'm not sure the others are useful since CIE2000 is the more recent refinement of much research on this topic, and is the most accurate of them.
* like bmp2dhr, only supports BMP source images in a particular format.
* Does not apply gamma correction before dithering (though sRGB conversion is done when computing CIE2000 distance), so errors are diffused non-linearly. The resulting images don't match the brightness of the original, e.g. shadows/highlights tend to be over-exposed.
* image conversion performs an optimization over groups of multiple pixels (via choice of "colour blocks"). From what I can tell this minimizes the total colour distance from a fixed list of colour blocks to a group of 4 target pixels, similar to --lookahead=4 for ][-pix (though I'm not sure it's evaluating all 2^4 pixel combinations). But since the image is (AFAICT) treated as a sequence of (non-overlapping) 4-pixel blocks this does not result in optimizing each output pixel independently.
* The list of "colour blocks" seem to contain colour sequences that cannot actually be rendered on the Apple II. For example compare the spacing of yellow and orange pixels on the parrot between the preview image (LHS) and openemulator (RHS):
![Detail of a2bestpix preview image](a2bestbix-preview-crop.png)
![Detail of openemulator render](a2bestpix-openemulator-crop.png)
* See below for another example where the output has major image discrepancies with the original - perhaps also due to bugs/omissions in the table of colour blocks.
* This means that (like bmp2dhr) the generated "preview" image may not closely match the native image, and the dithering algorithm is also optimizing over a slightly incorrect set of colour sequences, which presumably impacts image quality. Possibly these are transcription errors, or artifacts of the particular emulator (AppleWin) from which they were reconstructed.
## Image comparisons
These three images were converted using the same target (openemulator) palette, using ][-pix, bmp2dhr and a2bestpix (since this is supported by all three), and are shown as screenshots from openemulator.
### Original
![original source image](../examples/paperclips-original.png)
(Source: [Purple Sherbet Photography from Worldwide!](https://commons.wikimedia.org/wiki/File:Colourful_assortment_of_paper_clips_(10421946796).jpg), [CC BY 2.0](https://creativecommons.org/licenses/by/2.0), via Wikimedia Commons)
The following images were all generated with a palette approximating OpenEmulator's colours (`--palette=openemulator` for ][-pix)
### ][-pix 4-pixel colour
Preview image and OpenEmulator screenshot
![ii-pix preview](../examples/paperclips-iipix-openemulator-preview.png)
![ii-pix screenshot](../examples/paperclips-iipix-openemulator-openemulator.png)
### ][-pix NTSC 8-pixel colour (Preview image)
Preview image and OpenEmulator screenshot
![ii-pix preview](../examples/paperclips-iipix-ntsc-preview.png)
![ii-pix screenshot](../examples/paperclips-iipix-ntsc-openemulator.png)
### bmp2dhr (OpenEmulator screenshot)
![bmp2dhr screenshot](../examples/paperclips-bmp2dhr-openemulator.png)
Comparing bmp2dhr under openemulator is the scenario most favourable to it, since the 140px resolution and non-treatment of fringing is masked by the chroma blending. Colours are similar to ][-pix, but the 140px dithering and lack of gamma correction results in less detail, e.g. in hilights/shadows.
### a2bestpix (OpenEmulator screenshot)
![a2bestpix screenshot](../examples/paperclips-a2bestpix-openemulator.png)
This a2bestpix image is actually atypical in quality, and shows some severe colour errors relating to the pixels that should be close to the orange/brown colours. These may be due to errors/omissions in the set of "colour blocks". The effects of not gamma-correcting the source image can also be seen.
## NTSC artifacts
The difference in treatment of NTSC artifacts is much more visible when using an emulator that doesn't perform chroma subsampling, e.g. Virtual II. i.e. it displays the full 560-pixel colour image without blending.
### Original
![original source image](../examples/groundhog-original.png)
(Source: [Cephas](https://commons.wikimedia.org/wiki/File:Marmota_monax_UL_04.jpg), [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0), via Wikimedia Commons)
The following images were generated with a palette matching the one used by Virtual II (`--palette=virtualii` for ][-pix)
### ][-pix
![original source image](../examples/groundhog-original.png)
![ii-pix preview](../examples/groundhog-iipix-virtualii-preview.png)
### bmp2dhr
![original source image](../examples/groundhog-original.png)
![ii-pix screenshot](../examples/groundhog-bmp2dhr-virtualii.png)
The image is heavily impacted by colour fringing, which bmp2dhr does not account for at all. The difference in brightness of the groundhog's flank is also because bmp2dhr does not gamma-correct the image, so shadows/highlights tend to get blown out.
### bmp2dhr (OpenEmulator)
![original source image](../examples/groundhog-original.png)
![ii-pix screenshot](../examples/groundhog-bmp2dhr-openemulator.png)
This bmp2dhr image was generated using a palette approximating OpenEmulator's colours (`--palette=openemulator` for ][-pix), i.e. not the same image files as above.
On OpenEmulator, which simulates NTSC chroma sub-sampling, the fringing is not pronounced but changes the colour balance of the image, e.g. creates a greenish tinge.
### ][-pix, 4-pixel colour (OpenEmulator)
![original source image](../examples/groundhog-original.png)
![ii-pix screenshot](../examples/groundhog-iipix-openemulator-openemulator.png)
Colour balance here is also slightly distorted due to not fully accounting for chroma blending.
### ][-pix, NTSC 8-pixel colour (OpenEmulator)
![original source image](../examples/groundhog-original.png)
![ii-pix screenshot](../examples/groundhog-iipix-ntsc-openemulator.png)
Detail and colour balance is much improved.

View File

@ -10,12 +10,16 @@ import colour
import numpy as np
def main():
print("Precomputing conversion matrix from RGB to CAM16UCS colour space")
def srgb_to_linear_rgb_array(a: np.ndarray, gamma=2.4) -> np.ndarray:
return np.where(a <= 0.04045, a / 12.92, ((a + 0.055) / 1.055) ** gamma)
def main():
print("Precomputing conversion matrix from 24-bit RGB to CAM16UCS colour "
"space")
# Compute matrix of all 24-bit RGB values, normalized to 0..1 range
bits24 = np.arange(2 ** 24, dtype=np.uint32).reshape(-1, 1)
all_rgb = np.concatenate(
all_rgb24 = np.concatenate(
[bits24 >> 16 & 0xff, bits24 >> 8 & 0xff, bits24 & 0xff],
axis=1).astype(np.float32) / 255
del bits24
@ -23,10 +27,41 @@ def main():
with colour.utilities.suppress_warnings(colour_usage_warnings=True):
# Compute matrix of corresponding CAM16UCS colour values, indexed
# by 24-bit RGB value
all_cam16 = colour.convert(all_rgb, "RGB", "CAM16UCS").astype(
rgb24_to_cam16ucs = colour.convert(all_rgb24, "RGB", "CAM16UCS").astype(
np.float32)
del all_rgb
np.save("data/rgb_to_cam16ucs.npy", all_cam16)
del all_rgb24
np.save("data/rgb24_to_cam16ucs.npy", rgb24_to_cam16ucs)
del rgb24_to_cam16ucs
print("Precomputing conversion matrix from 12-bit //gs RGB to CAM16UCS "
"colour space")
# Compute matrix of all 12-bit RGB values, normalized to 0..1 range
bits12 = np.arange(2 ** 12, dtype=np.uint32).reshape(-1, 1)
r = bits12 >> 8
g = (bits12 >> 4) & 0xf
b = bits12 & 0xf
all_rgb12 = np.concatenate(
[(r << 4) | r, (g << 4) | g, (b << 4) | b], axis=1).astype(
np.float32) / 255
del bits12, r, g, b
# //gs RGB values use gamma-corrected Rec.601 RGB colour space. We need to
# convert to Rec.709 RGB as preparation for converting to CAM16UCS. We
# do this via the YCbCr intermediate color model.
rgb12_iigs = np.clip(srgb_to_linear_rgb_array(
np.clip(colour.YCbCr_to_RGB(
colour.RGB_to_YCbCr(
all_rgb12, K=colour.WEIGHTS_YCBCR[
'ITU-R BT.601']),
K=colour.WEIGHTS_YCBCR['ITU-R BT.709']), 0, 1)), 0, 1)
with colour.utilities.suppress_warnings(colour_usage_warnings=True):
# Compute matrix of corresponding CAM16UCS colour values, indexed
# by 12-bit //gs RGB value
rgb12_iigs_to_cam16ucs = colour.convert(
rgb12_iigs, "RGB", "CAM16UCS").astype(np.float32)
del rgb12_iigs
np.save("data/rgb12_iigs_to_cam16ucs.npy", rgb12_iigs_to_cam16ucs)
del rgb12_iigs_to_cam16ucs
if __name__ == "__main__":

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
colour-science
Cython
networkx
numpy
Pillow
pygame
scikit-learn

View File

@ -5,6 +5,68 @@ import numpy as np
import palette as palette_py
class SHR320Screen:
X_RES = 320
Y_RES = 200
def __init__(self):
self.palettes = {k: np.zeros((16, 3), dtype=np.uint8) for k in
range(16)}
# Really 4-bit values, indexing into palette
self.pixels = np.array((self.Y_RES, self.X_RES), dtype=np.uint8)
# Choice of palette per scan-line
self.line_palette = np.zeros(self.Y_RES, dtype=np.uint8)
self.memory = None
def set_palette(self, idx: int, palette: np.array):
if idx < 0 or idx > 15:
raise ValueError("Palette index %s must be in range 0 .. 15" % idx)
if palette.shape != (16, 3):
raise ValueError("Palette size %s != (16, 3)" % palette.shape)
# XXX check element range
if palette.dtype != np.uint8:
raise ValueError("Palette must be of type np.uint8")
# print(palette)
self.palettes[idx] = np.array(palette)
def set_pixels(self, pixels):
self.pixels = np.array(pixels)
def pack(self):
dump = np.zeros(32768, dtype=np.uint8)
for y in range(self.Y_RES):
pixel_pair = 0
for x in range(self.X_RES):
if x % 2 == 0:
pixel_pair |= (self.pixels[y, x] << 4)
else:
pixel_pair |= self.pixels[y, x]
# print(pixel_pair)
dump[y * 160 + (x - 1) // 2] = pixel_pair
pixel_pair = 0
scan_control_offset = 320 * 200 // 2
for y in range(self.Y_RES):
dump[scan_control_offset + y] = self.line_palette[y]
palette_offset = scan_control_offset + 256
for palette_idx, palette in self.palettes.items():
for rgb_idx, rgb in enumerate(palette):
r, g, b = rgb
assert r <= 15 and g <= 15 and b <= 15
# print(r, g, b)
rgb_low = (g << 4) | b
rgb_hi = r
# print(hex(rgb_hi), hex(rgb_low))
palette_idx_offset = palette_offset + (32 * palette_idx)
dump[palette_idx_offset + (2 * rgb_idx)] = rgb_low
dump[palette_idx_offset + (2 * rgb_idx + 1)] = rgb_hi
self.memory = dump
class DHGRScreen:
X_RES = 560
Y_RES = 192

View File

@ -6,7 +6,7 @@ Cython.Compiler.Options.annotate = True
setup(
ext_modules=cythonize(
["dither.pyx"],
["common.pyx", "dither_dhr.pyx", "dither_shr.pyx"],
annotate=True,
compiler_directives={'language_level': "3"}
)