Sort all the pixels of an image by the number of occurrences Input

The name of a file in the raster graphics format of your choice. The chosen format must support at least 8 bits per channel and 3 channels.

Output

A file in the same format, with the same dimensions and pixels as the first, but whose pixels are grouped in descending order of the number of times they occur, sorted from left-to-right, top-to-bottom.


If certain colours of pixels appear the same number of times, their order is unspecified.
You must not overwrite the input file (use a different file name for the output).
Any and all third-party image processing libraries are permitted.


Example



Will give output similar to:



Especially in the lower parts of the image some variation may occur, due to different tie breaking between colours of equal frequency.
Mathematica, 125 123 bytes

Export["a"&lt;&gt;#,i=ImageData@Import@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&amp;],Dimensions@i]]&amp;


This defines an unnamed function which takes the file name in any common image format and writes the result to the a file with the same name but prepended with a. The result looks a bit different from the OP's, since Mathematica's SortBy breaks ties by default sort order, so the bottom bits where loads of ties occur look a bit neater:



The implementation itself is really straightforward:


ImageData to get a grid of colour values.
Join to flatten the array.
Tally to count the occurrence of each colour.
SortBy[...,-Last@#&amp;] to sort by frequencies from highest to lowest.
ConstantArray and Join to expand the tallies again.
ArrayReshape to recover the original image shape (obtained with Dimensions).
Image to convert the data back to an image object.


FYI, 22 bytes are used on file I/O. An equivalent version that takes and returns an image object comes in at 103 bytes:

(i=ImageData@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&amp;],Dimensions@i])&amp;