1
$\begingroup$

I have a csv file with lots of RGB colours (in 3 columns, r, g, b). I want to use that data to make an array of cubes, one cube per RGB value. I want to use the RGB to specify the x,y,z coordinates and ideally the colour of the cube material. (This second step is less important; I'd be happy with just the first step for now.)

This intuitively feels like a do-able thing, but I'm a noob in Blender and from watching some tutorials on using csv data, I don't feel I understand enough to adapt any techniques to doing this problem. Grateful for any help!

$\endgroup$
1

1 Answer 1

2
$\begingroup$

Head over to the Scripting tab, create a new python file and paste this code (of course change <your path to> to your locations):

import bpy
import csv

with open('<your path to>/rgb.csv') as csvfile:
    
    reader = csv.reader(csvfile, delimiter=',')
    
    currline = -1
    for row in reader:
        currline += 1
        
        if currline == 0: # ignore header line
            print(f'columns: {" ".join(row)}')
            continue
            
        r = float(row[0])
        g = float(row[1])
        b = float(row[2])

        volume = 10 # span cubes in space
        bpy.ops.mesh.primitive_cube_add(
            enter_editmode = False,
            size     = 1,
            align    = 'WORLD',
            location = (r * volume, g * volume, b * volume), # use (r g b) for (x y z)
            scale    = (1, 1, 1)
        )
        bpy.context.active_object.name = 'row ' + str(currline)   # name cube with data row
        mat = bpy.data.materials.new(name = str(r) + ',' +str(g) + ',' + str(b)) # name mat with (r g b)
        mat.diffuse_color = (r, g, b, 1)
        
        bpy.context.active_object.data.materials.append(mat)

With a test .csv layouted like so

r,g,b,
0.1,0.1,1,
0.1,0.2,1,
0.1,0.3,1,
0.6,0.1,0.4,
0.7,0.1,0.2,
0.1,0.1,0.5,

you get the following result:

enter image description here

Edit: diffuse_color is only the color in the viewport, which may raise confusion. Changing the "real" color takes a bit more like described here.

$\endgroup$
2
  • $\begingroup$ Amazing, thank you, that works! With the colour, I realise now that as well as changing the real colour as you mention in your edit, the RGB data is in 0-255 format, so I'll also need to convert it to 0-1. $\endgroup$
    – RobNUL
    Commented Jul 6, 2023 at 12:49
  • $\begingroup$ You can also use the more pythonic for currline, row in enumerate(reader): which takes care of incrementing the variable $\endgroup$
    – Gorgious
    Commented Jul 6, 2023 at 14:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .