ex14_volume_section
This is an example for a scripted ‘volume section’ element. The dialog allows to select an image file, which is converted to a grayscale image (calculation()
, line 30) and then to an np.array()
(line 32). Further, a transformation is applied to the image.
Note
Please see offset_point_v2.md for a complete scripted elements example with detailed description.
Source code excerpt
1import numpy as np
2from math import sin, cos
3from PIL import Image
4from io import BytesIO
5
6def dialog(context, params):
7 #[...]
8
9def calculation(context, params):
10 valid_results = False
11
12 file = params['file']
13
14 # if filename starts with ':', it is an add-on resource used for testing,
15 # e.g. ':ScriptedElementsExamples/Grayscale_8bits_palette.png'
16 if file and file[0] == ':':
17 # read resource
18 test_image_resource = gom.Resource(file)
19 test_image = test_image_resource.open().read()
20
21 # convert resource to file object
22 file = BytesIO(test_image)
23
24 try:
25 image = Image.open(file)
26 except AttributeError:
27 return False
28
29 # convert image to grayscale
30 image = image.convert('L')
31 # print (image)
32 img_array = np.array(image, dtype=np.float32)
33 # print(f"img_array: {img_array}")
34 # print(f"img_array.shape: {img_array.shape}")
35
36 rx = params['rx']
37 ry = params['ry']
38 rz = params['rz']
39 dx = params['dx']
40 dy = params['dy']
41 dz = params['dz']
42
43 transformation = gom.Mat4x4([
44 cos(rz) * cos(ry), cos(rz) * sin(ry) * sin(rx) - sin(rz) *
45 cos(rx), cos(rz) * sin(ry) * cos(rx) + sin(rz) * sin(rx), dx,
46 sin(rz) * cos(ry), sin(rz) * sin(ry) * sin(rx) + cos(rz) *
47 cos(rx), sin(rz) * sin(ry) * sin(rx) - cos(rz) * sin(rx), dy,
48 -sin(ry), cos(ry) * sin(rx), cos(ry) * cos(rx), dz,
49 0, 0, 0, 1
50 ])
51 # print(transformation)
52
53 # Calculating all available stages
54 for stage in context.stages:
55 # Access element properties with error handling
56 try:
57 context.result[stage] = {
58 'pixel_data': img_array,
59 'transformation': transformation
60 }
61 context.data[stage] = {"ude_mykey": "Example 14"}
62 except Exception as error:
63 context.error[stage] = str(error)
64 else:
65 valid_results = True
66 return valid_results