Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Photo Mosaic in Mathematica: an example from 2008 doesn't work in Mathematica 8

I'm trying to get a Mathematica example working. It's the one on Theo Gray's blog.

I think that Mathematica must have changed since he wrote that code (May 2008), since I'm unable to get anything reasonable out of it, despite changing nearly everything. Do I use ImageData instead of Import? Can anyone suggest a version of this code that works for Mathematica 8?

imagePool = 
 Map[With[{i = Import[#]}, {i, Mean[Flatten[N[i[[1, 1]]], 1]]}] &, 
  FileNames["Pool/*.jpg"]];
closeMatch[c_] := 
  RandomChoice[Take[SortBy[imagePool, Norm[c - #[[2]]] &], 20]][[1]];
Grid[Reverse[
  Map[closeMatch, Import["MendeleevIcon.tif"][[1, 1]], {2}]], 
  Spacings -> {0, 0}]
like image 835
cormullion Avatar asked Oct 22 '11 15:10

cormullion


2 Answers

Maybe slightly more streamlined:

imagePool = Map[With[{i = Import[#]}, {i, N@Mean[Flatten[ImageData[i], 1]]}] &, 
   FileNames["Pool/*.jpg"]];

closeMatch[c_] := RandomChoice[
   Nearest[imagePool[[All, 2]] -> imagePool[[All, 1]], c, 20]]

ImageAssemble[Map[closeMatch, ImageData[Import["mendeleevIcon.tif"]], {2}]]

mosaic

Edit

The reason that the original code stopped working in version 8 is that up until version 6 of Mathematica, Import["file.jpg"] would return a Graphics[Raster[]] object. To extract the image data itself you could simply do Import["file.jpg"][[1,1]]. However, in version 8 (and I suspect version 7) raster images are imported as an Image by default which means that you need ImageData to extract the image data from the imported files. You can still import raster images as a Graphics[Raster[]] by using Import["file.jpg","Graphics"] so the original code should still work if you adapt the Import statements, but the advantage of using Image objects is that you can use functions such as ImageAssemble (plus a whole range of other image processing tools that comes with Mathematica 8).

like image 145
Heike Avatar answered Oct 19 '22 06:10

Heike


The following works (Thanks to @yoda for pointing out the Reverse[] thing in the comments):

f = FileNames["*.jpg", {"c:\\test\\pool\\Pool"}];
m = Import["c:\\test\\pool\\Pool\\MendeleevIcon.tif"];
imagePool =
  Map[
   With[{i = Import[#]},
     {i, Mean[Flatten[ImageData@i, 1]]}] &, f];
closeMatch[c_] := 
  RandomChoice[Take[SortBy[imagePool, Norm[c - #[[2]]] &], 20]][[1]];
Grid[Map[closeMatch, ImageData@m, {2}], Spacings -> {0, 0}]

enter image description here

like image 5
Dr. belisarius Avatar answered Oct 19 '22 06:10

Dr. belisarius