-
Notifications
You must be signed in to change notification settings - Fork 3
/
json_image_to_blender.py
73 lines (59 loc) · 2.11 KB
/
json_image_to_blender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
"""
Loads a file of pixel values and converts to bar heights for use in Blender.
"""
import sys
import bpy
import json
# Initialize scene and primitive
bpy.ops.object.select_all(action="DESELECT")
bpy.ops.mesh.primitive_cube_add()
cube = bpy.context.object
cube.scale = (0.1, 0.1, 0.1)
# Add colors in the user-specified map
for i in range(256):
key = "L%d" % i
bpy.data.materials.new(name=key)
# Convert [0, 255] to (r, g, b)
bpy.data.materials[key].diffuse_color = [i / 255.0] * 3 + [1]
bpy.data.materials[key].specular_intensity = 0.02
def pixels_to_blender(pixels, z_scale=0.05):
""" Iterates through pixels and draws vertical bars """
collection = bpy.data.collections.new('pixels')
bpy.context.scene.collection.children.link(collection)
# Keep references to all pixels
shapes = []
# Iterate through data an make bars
for y, row in enumerate(pixels):
print("Processing column %d" % (y + 1))
for x, pixel in enumerate(row):
# Copy a cube primitive
bar = cube.copy()
bar.data = cube.data.copy()
size = cube.scale.z
# Move and scale
bar.location = (2 * size * x, -2 * size * y,
size * pixel * z_scale)
bar.data.materials.append(bpy.data.materials["L%d" % pixel])
bar.scale.z *= pixel * z_scale
# Link to scene and save
shapes.append(bar)
collection.objects.link(bar)
# Remove primitive meshes
bpy.ops.object.select_all(action='DESELECT')
cube.select_set(True)
# If the starting cube is there, remove it
if "Cube" in bpy.data.objects.keys():
bpy.data.objects.get('Cube').select_set(True)
bpy.ops.object.delete()
# Join pixel shapes
for shape in shapes:
shape.select_set(True)
bpy.context.view_layer.objects.active = shapes[0]
bpy.ops.object.join()
# Read json data and run through Blender
if __name__ == "__main__":
pixels = sys.argv[-1]
with open('pixels.json') as indata:
pixels = json.load(indata)
pixels_to_blender(pixels)