{"id":3520,"date":"2011-08-19T23:15:55","date_gmt":"2011-08-20T06:15:55","guid":{"rendered":"http:\/\/multimedia.cx\/eggs\/?p=3520"},"modified":"2020-07-25T21:49:59","modified_gmt":"2020-07-26T04:49:59","slug":"basic-video-palette-conversion","status":"publish","type":"post","link":"https:\/\/multimedia.cx\/eggs\/basic-video-palette-conversion\/","title":{"rendered":"Basic Video Palette Conversion"},"content":{"rendered":"<p>How do you take a 24-bit RGB image and convert it to an 8-bit paletted image for the purpose of compression using a codec that requires 8-bit input images? Seems simple enough and that&#8217;s what I&#8217;m tackling in this post.<\/p>\n<p><strong>Ask FFmpeg\/Libav To Do It<\/strong><br \/>\nIdeally, <a href=\"http:\/\/ffmpeg.org\/\">FFmpeg<\/a> \/ <a href=\"http:\/\/libav.org\/\">Libav<\/a> should be able to handle this automatically. Indeed, FFmpeg used to be able to, at least at the time I <a href=\"http:\/\/multimedia.cx\/eggs\/zmbv-tinkering\/\">wrote this post about ZMBV<\/a> and was unhappy with FFmpeg&#8217;s default results. Somewhere along the line, FFmpeg and Libav lost the ability to do this. I suspect it got removed during some swscale refactoring.<\/p>\n<p>Still, there&#8217;s no telling if the old system would have computed palettes correctly for QuickTime files.<\/p>\n<p><strong>Distance Approach<\/strong><br \/>\nWhen I started <a href=\"http:\/\/multimedia.cx\/eggs\/creating-a-lossless-smc-encoder\/\">writing my SMC video encoder<\/a>, I needed to convert RGB (from PNG files) to PAL8 colorspace. The path of least resistance was to match the pixels in the input image to the default 256-color palette that QuickTime assumes (and is hardcoded into FFmpeg\/Libav).<\/p>\n<p>How to perform the matching? Find the palette entry that is closest to a given input pixel, where &#8220;closest&#8221; is the minimum distance as computed by the usual distance formula (square root of the sum of the squares of the diffs of all the components).<\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2011\/08\/palette-distance-formula.png\" alt=\"\" title=\"Palette distance formula\" width=\"208\" height=\"44\" class=\"aligncenter size-full wp-image-3521\" \/><br \/>\n<\/center><\/p>\n<p>That means for each pixel in an image, check the pixel against 256 palette entries (early termination is possible if an acceptable threshold is met). As you might imagine, this can be a bit time-consuming. I wondered about a faster approach&#8230;<\/p>\n<p><strong>Lookup Table<\/strong><br \/>\n<!--more-->I think this is the approach that FFmpeg used to use, but I went and derived it for myself after studying the default QuickTime palette table. There&#8217;s a pattern there&#8211; all of the RGB entries are comprised of combinations of 6 values &#8212; 0x00, 0x33, 0x66, 0x99, 0xCC, and 0xFF. If you mix and match these for red, green, and blue values, you come up with  <code>6 * 6 * 6 = 216<\/code> different colors. This happens to be identical to <a href=\"http:\/\/en.wikipedia.org\/wiki\/Web_colors\">the web-safe color palette<\/a>.<\/p>\n<p>The first (0th) entry in the table is (FF, FF, FF), followed by (FF, FF, CC), (FF, FF, 99), and on down to (FF, FF, 00) when the green component gets knocked down and step and the next color is (FF, CC, FF). The first 36 palette entries in the table all have a red component of 0xFF. Thus, if an input RGB pixel has a red color closest to 0xFF, it must map to one of those first 36 entries.<\/p>\n<p>I created a table which maps indices 0..215 to values from 5..0. Each of the R, G, and B components of an input pixel are used to index into this table and derive 3 indices ri, gi, and bi. Finally, the index into the palette table is given by:<\/p>\n<pre>\r\n  index = ri * 36 + gi * 6 + bi\r\n<\/pre>\n<p>For example, the pixel (0xFE, 0xFE, 0x01) would yield ri, gi, and bi values of 0, 0, and 5. Therefore:<\/p>\n<pre>\r\n  index = 0 * 36 + 0 * 6 + 5\r\n<\/pre>\n<p>The palette index is 5, which maps to color (0xFF, 0xFF, 0x00).<\/p>\n<p><strong>Validation<\/strong><br \/>\nSo I was pretty pleased with myself for coming up with that. Now, ideally, swapping out one algorithm for another in my SMC encoder should yield identical results. That wasn&#8217;t the case, initially.<\/p>\n<p>One problem is that the regulation QuickTime palette actually has 40 more entries above and beyond the typical 216-entry color cube (rounding out the grand total of 256 colors). Thus, using the distance approach with the full default table provides for a little more accuracy.<\/p>\n<p>However, there still seems to be a problem. Let&#8217;s check our old standby, the Big Buck Bunny logo image:<\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2011\/08\/bbb-title-distance-full-palette.png\" alt=\"\" title=\"Logo, full QuickTime color palette using distance approach\" width=\"300\" height=\"200\" class=\"aligncenter size-full wp-image-3524\" \/><br \/>\n<em>Distance approach using the full 256-color QuickTime default palette<\/em><br \/>\n<\/center><\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2011\/08\/bbb-title-distance.png\" alt=\"\" title=\"Logo, 216-color palette using distance approach\" width=\"300\" height=\"200\" class=\"aligncenter size-full wp-image-3525\" \/><br \/>\n<em>Distance approach using the 216-color palette<\/em><br \/>\n<\/center><\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2011\/08\/bbb-title-table.png\" alt=\"\" title=\"Logo, using 216-palette and table lookup approach\" width=\"300\" height=\"200\" class=\"aligncenter size-full wp-image-3526\" \/><br \/>\n<em>Table lookup approach using the 216-color palette<\/em><br \/>\n<\/center><\/p>\n<p>I can&#8217;t quite account for that big red splotch there. That&#8217;s the most notable difference between images 1 and 2 and the only visible difference between images 2 and 3.<\/p>\n<p>To prove to myself that the distance approach is equivalent to the table approach, I wrote a Python script to iterate through all possible RGB combinations and verify the equivalence. If you&#8217;re not up on your base 2 math, that&#8217;s 2<sup>24<\/sup> or 16,777,216 colors to run through. I used <a href=\"http:\/\/docs.python.org\/library\/multiprocessing.html\">Python&#8217;s multiprocessing<\/a> module to great effect and really maximized a Core i7 CPU with 8 hardware threads.<\/p>\n<p>So I&#8217;m confident that the palette conversion techniques are sound. The red spot is probably attributable to a bug in my WIP SMC encoder.<\/p>\n<p><strong>Source Code<\/strong><br \/>\n<em>Update August 23, 2011:<\/em> Here&#8217;s the Python code I used for proving equivalence between the 2 approaches. In terms of leveraging multiple CPUs, it&#8217;s possibly the best program I have written to date.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/multimediamike\/67bddc00883f9907bb94af4440d8a5ca.js\"><\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Brainstorming different methods for transforming a full-color RGB image into one that has to rely on 256 colors<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,55],"tags":[],"class_list":["post-3520","post","type-post","status-publish","format-standard","hentry","category-general","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3520","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/comments?post=3520"}],"version-history":[{"count":12,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3520\/revisions"}],"predecessor-version":[{"id":4567,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3520\/revisions\/4567"}],"wp:attachment":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/media?parent=3520"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/categories?post=3520"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/tags?post=3520"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}