# Image regeneration with nearest neighbor search

So what I would like to achieve is this:

1. User submits Image 1 - this image is then broken down into X by X sized blocks
2. User submits Image 2 - then the program/algorithm takes all the blocks generated in the above step, and reconstructs Image 2 using them

Example Image 2:

Example Output:

What I would like to know is, are there any libraries, or some easy way of doing this (ideally in Javascript, as I don't know any other languages) - or even some standalone software tool to accomplish this?

• Is image 2 somehow broken? Or are you in fact trying to figure out disparity to then operate on the second image somehow. Like making colors uniform or something. Commented May 12, 2017 at 14:59
• @joojaa, no, sorry for not being clearer. Image 2 is a perfect image/photo. What the aim of the algorithm is, is to take blocks of a totally different image (Image 1) - say for example comic book scans, and use that to re-draw image 2, purely for the artistic effect. Commented May 12, 2017 at 15:14
• Added example images to clarify. Commented May 12, 2017 at 15:16
• ...Or you could just grab Mosaic program (maybe from brighthub.com/multimedia/photography/articles/34691.aspx ). The only tedious part would be manufacturing a set of images to corresponding to your blocks. Commented May 12, 2017 at 16:21
• For the case X=1 you might want to take a look here: codegolf.stackexchange.com/questions/33172/… One solution you could think of is reducing each X by X square to one colour (e.g. by averaging) and then using the algorithm presented in the linked challenge. Commented May 18, 2017 at 22:09

## 1 Answer

I would have done it with a script and NETPBM like so:

1) reducing Image1 (the tiles) to size X by X -> Image1R

2) recording the mapping from pixel values of Image1R to coordinates (no need to worry about duplicates as an exact RGB match of two or more averaged pixels is unlikely)

3) remapping Image2 using Image1R as the color map -> Image2M

4) reading pixels of Image2M, consulting the map, and picking the tile corresponding to the coordinates

5) concatenating the selected tiles across and down

There is a separate tool for all the above image manipulations in NETPBM.

Any scripting language that allows spawning other processes and supports associative arrays, would do.