LEGO Artworks - Generativ Art with Python

In case you want to try it, here is the script:
You have to model a Lego-brick at first. That shouldn’t be a problem :wink:

This is the setup:



"""
This script copies an object based on an image input and sets the vertex color to the corresponding pixels.
Make sure that the image is already scaled down and is loaded into the blend file. 
One side of the image should not be larger than 20px. It takes some time ;)
But if you have time feel free to go larger.

1. Change the image name to your image input
2. Make sure the object you want to clone is selected
3. Run the Script!
4. In the shader network you can access the color with the attribute node. 

"""

import bpy

# get image data, image has to be loaded into the blend-file
img = bpy.data.images["image.jpg"]
width = img.size[0]
height = img.size[1]

#get object-size for grid (has to be square)
obj = bpy.context.active_object
size = obj.dimensions[0]

#create new collection if necessary
if bpy.data.collections.get("LegoGrid") is None:
    grid_coll = bpy.data.collections.new("LegoGrid")
    bpy.context.scene.collection.children.link(grid_coll)
else:
    grid_coll = bpy.data.collections["LegoGrid"]
    
#generate grid and match pixeldata to vertex color
for y in range(height):
    for x in range(width):
        copy = obj.copy()
        copy.data = obj.data.copy()
        
        copy.location = x*size,y*size,0
        
        mesh = copy.data
        if not mesh.vertex_colors:
            mesh.vertex_colors.new()
        
        color_layer = mesh.vertex_colors["Col"]
        
        index = (y * width + x) * 4
        
        r = img.pixels[index + 0]
        g = img.pixels[index + 1]
        b = img.pixels[index + 2]
        a = img.pixels[index + 3]

        i = 0
        for poly in mesh.polygons:
            for idx in poly.loop_indices:
                rgb = [r,g,b,a]
                color_layer.data[i].color = rgb
                i += 1
                
        grid_coll.objects.link(copy)
11 Likes