forked from njanakiev/blender-scripting
/
fisher_iris_visualization.py
212 lines (168 loc) · 6.62 KB
/
fisher_iris_visualization.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import bpy
import bmesh
import numpy as np
import utils
from mathutils import Vector, Matrix
from math import pi
def PCA(data, num_components=None):
# mean center the data
data -= data.mean(axis=0)
# calculate the covariance matrix
R = np.cov(data, rowvar=False)
# calculate eigenvectors & eigenvalues of the covariance matrix
# use 'eigh' rather than 'eig' since R is symmetric,
# the performance gain is substantial
V, E = np.linalg.eigh(R)
# sort eigenvalue in decreasing order
idx = np.argsort(V)[::-1]
E = E[:,idx]
# sort eigenvectors according to same index
V = V[idx]
# select the first n eigenvectors (n is desired dimension
# of rescaled data array, or dims_rescaled_data)
E = E[:, :num_components]
# carry out the transformation on the data using eigenvectors
# and return the re-scaled data, eigenvalues, and eigenvectors
return np.dot(E.T, data.T).T, V, E
def load_iris():
try:
# Load Iris dataset from the sklearn.datasets package
from sklearn import datasets
from sklearn import decomposition
# Load Dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
labels = iris.target_names
# Reduce components by Principal Component Analysis from sklearn
X = decomposition.PCA(n_components=3).fit_transform(X)
except ImportError:
# Load Iris dataset manually
path = os.path.join('data', 'iris', 'iris.data')
iris_data = np.genfromtxt(path, dtype='str', delimiter=',')
X = iris_data[:, :4].astype(dtype=float)
y = np.ndarray((X.shape[0],), dtype=int)
# Create target vector y and corresponding labels
labels, idx = [], 0
for i, label in enumerate(iris_data[:, 4]):
label = label.split('-')[1]
if label not in labels:
labels.append(label); idx += 1
y[i] = idx - 1
# Reduce components by implemented Principal Component Analysis
X = PCA(X, 3)[0]
return X, y, labels
def createScatter(X, y, size=0.25):
labelIndices = set(y)
colors = [(1, 0, 0,1), (0, 1, 0,1), (0, 0, 1,1), \
(1, 1, 0,1), (1, 0, 1,1), (0, 1, 1,1)]
# Create a bmesh for each label
bmList = []
for labelIdx in labelIndices:
bmList.append(bmesh.new())
# Iterate through all the vectors and targets
for x, labelIdx in zip(X, y):
# Use the vector as translation for each point
T = Matrix.Translation(x)
if labelIdx % 3 == 0:
bmesh.ops.create_cube(bmList[labelIdx],
size=size, matrix=T)
elif labelIdx % 3 == 1:
bmesh.ops.create_icosphere(bmList[labelIdx],
diameter=size/2, matrix=T)
else:
bmesh.ops.create_cone(bmList[labelIdx],
segments=6, cap_ends=True,
diameter1=size/2, diameter2=0,
depth=size, matrix=T)
objects = []
for labelIdx, color in zip(labelIndices, colors):
# Create a mesh from the existing bmesh
mesh = bpy.data.meshes.new('ScatterMesh {}'.format(labelIdx))
bmList[labelIdx].to_mesh(mesh)
bmList[labelIdx].free()
# Create a object with the mesh and link it to the scene
obj = bpy.data.objects.new('ScatterObject {}'.format(labelIdx), mesh)
#bpy.context.scene.objects.link(obj)
bpy.context.collection.objects.link(obj)
# Create materials for each bmesh
mat = bpy.data.materials.new('ScatterMaterial {}'.format(labelIdx))
mat.diffuse_color = color
# mat.diffuse_intensity = 0.5
mat.specular_intensity = 0.0
obj.data.materials.append(mat)
objects.append(obj)
def createLabels(X, y, labels, cameraObj=None):
labelIndices = set(y)
objects = []
# Draw labels
for labelIdx in labelIndices:
center = np.sum([x for x, idx in zip(X, y) \
if idx == labelIdx], axis=0)
counts = (y == labelIdx).sum()
center = Vector(center) / counts
label = labels[labelIdx]
fontCurve = bpy.data.curves.new(type="FONT", name=label)
fontCurve.body = label
fontCurve.align_x = 'CENTER'
fontCurve.align_y = 'BOTTOM'
fontCurve.size = 0.6
obj = bpy.data.objects.new("Label {}".format(label), fontCurve)
obj.location = center + Vector((0, 0, 0.8))
obj.rotation_mode = 'AXIS_ANGLE'
obj.rotation_axis_angle = (pi/2, 1, 0, 0)
# bpy.context.scene.objects.link(obj)
bpy.context.collection.objects.link(obj)
if cameraObj is not None:
constraint = obj.constraints.new('LOCKED_TRACK')
constraint.target = cameraObj
constraint.track_axis = 'TRACK_Z'
constraint.lock_axis = 'LOCK_Y'
objects.append(obj)
#bpy.context.scene.update()
bpy.context.view_layer.update()
return objects
if __name__ == '__main__':
# Remove all elements
utils.removeAll()
# Set ambient occlusion
utils.setAmbientOcclusion()
# Create camera and lamp
targetObj, cameraObj, lampObj = utils.simpleScene(
(0, 0, 0), (6, 6, 3.5), (-5, 5, 10))
# Make target as parent of camera
cameraObj.parent = targetObj
# Set number of frames
bpy.context.scene.frame_end = 50
# Animate rotation of target by keyframe animation
targetObj.rotation_mode = 'AXIS_ANGLE'
targetObj.rotation_axis_angle = (0, 0, 0, 1)
targetObj.keyframe_insert(data_path='rotation_axis_angle', index=-1,
frame=bpy.context.scene.frame_start)
targetObj.rotation_axis_angle = (2*pi, 0, 0, 1)
# Set last frame to one frame further to have an animation loop
targetObj.keyframe_insert(data_path='rotation_axis_angle', index=-1,
frame=bpy.context.scene.frame_end + 1)
# Change each created keyframe point to linear interpolation
for fcurve in targetObj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
X, y, labels = load_iris()
createScatter(X, y)
createLabels(X, y, labels, cameraObj)
# Create a grid
bpy.ops.mesh.primitive_grid_add(
size=3,
location=(0, 0, 0),
x_subdivisions=15,
y_subdivisions=15)
grid = bpy.context.active_object
# Create grid material
gridMat = bpy.data.materials.new('GridMaterial')
# TODO add a wireframe modifier
#gridMat.type = 'WIRE'
#gridMat.use_transparency = True
#gridMat.alpha = 0.3
grid.data.materials.append(gridMat)
utils.renderToFolder('frames', 'fisher_iris_visualization', 500, 500,
animation=True)