Photo Mosaic in Mathematica: an example from 2008 does not work in Mathematica 8

I am trying to get an example of Mathematica. This is the one on Theo Gray's blog .

I think that Mathematica must have changed since he wrote this code (May 2008), since I can’t get anything reasonable out of it, even though I am changing almost everything. 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}] 
+6
source share
2 answers

The following works (thanks @yoda for pointing to Reverse[] 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

+5
source

Perhaps a little more optimized:

 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 the source code stops working in version 8 is because, prior to Mathematica version 6, Import["file.jpg"] will return a Graphics[Raster[]] object. To extract the image data, you can simply do Import["file.jpg"][[1,1]] . However, in version 8 (and I suspect version 7), bitmaps are imported as Image by default, which means that you need ImageData to extract image data from the imported files. You can import bitmaps as Graphics[Raster[]] using Import["file.jpg","Graphics"] so that the source code works anyway if you adapt Import statements, but the advantage of using Image objects is that you can use features like ImageAssemble (plus a host of other image processing tools that come with Mathematica 8).

+7
source

Source: https://habr.com/ru/post/899872/


All Articles