LEGO mosaics, Part 3(D)


Last year, I wrote a post sharing some functions in R to generate LEGO Mosaics from an image and another to improve on those functions and provide tools to turn those digital mosaics into actual LEGO sets.

In those blog posts, I described the process of converting an image into LEGO colors and then grouping similar colors into LEGO bricks. The whole process is laid out below. The first section performs all the calcuations to generate the mosaic object. The display_set() function produces the graphic.

LegoMosaic <- readJPEG("LEGOMosaic/goldengirls.jpg") %>% 
  scale_image(c(56, 48)) %>% #Single value for square, c(W, H) for rectangle
  legoize() %>% 

LegoMosaic %>% 

This was a super fun project for me to build. Almost a year later, I’m revisiting it to add some more features.

3D Mosaics!

Recently, Tyler Morgan-Wall released a new package to create 3D hillshaded maps in R. I don’t work with that type of data, but opportunity to misuse his work for my LEGO mosaics was immediately evident.

In order to do this, I added two new functions to the project:

  • collect_3d() translates the 2D LEGO mosaic object from collect_bricks() into the data needed for the 3D rendering, complete with round studs on top of each brick. By default, the produced image has the height of 6 LEGO plates (2 LEGO bricks) with lighter colors having a higher elevation. Both of these assumptions can be changed.

  • display_3d() simply calls rayshader::plot_3d() (I can’t take credit for this part!), but pulls both the hillshade and elevation matrices from the output of collect_3d() and freezes the zscale value so that the image actually resembles bricks.

To convert our 2D mosaic into a 3D image, pass the mosaic object into the new functions rather than display_set().


LegoMosaic %>% 
  collect_3d() %>% 


GIF it!

You can add to the 3D excitement by converting the image to an animated GIF. For this, I used a tutorial by Will Bishop to iteratively generate different angles of the mosaic and string them together. It looks like a new feature might be coming to the package to make this process easier.

Color Themes

By filtering the rows in the Colors/Lego_Colors.csv file, you can limit the colors used in the mosaics. This is convenient if you want to actually build a mosaic with LEGO bricks you have available.

I’ve also added an option to create grayscale mosaics, much like the original LEGO Mosaic Maker. You can use legoize(theme='bw') to generate the mosaic in the four gray colors. You can also set the contrast input to be less than or greater than 1 to adjust the allocation of colors.

readJPEG("LEGOMosaic/goldengirls.jpg") %>% 
  scale_image(48) %>%
  legoize(theme='bw', contrast = 1.25) %>% 
  collect_bricks() %>% 


I think the next step is to actually build one of these things. And seriously… next time I open up this project, I’ll turn it into a package. 🤷

Try it out! Full script can be found on GitHub!

Ryan Timpe
Data Science | Economics