Calc Results By Python: Image Slicing

Observation

When defining an image slicing function in the Calc Results By Python step one can encounter a problem:
Simply returning the sliced input image creates an unexpected problem, when slicing along the second dimension, see Fig.3. The reason is that the memory of the input image is contiguous. When returning only a part of the image (since it was sliced) the data is referenced, and the referenced data is not continuous. As a result, the returned content cannot avoid the “useless” data section, that’s why you see the images get weird. To fix this issue simply use copy() right at the end of the function, e.g.:

def slice_image_hor(image):
image = image[300:800,:] # no problems
return image

def slice_image_ver(image):
image = image[:,300:800] # contiguous data problem
image = image.copy() # fixes the contiguous data issue
return image


Fig.1 : Original Image


Fig. 2: Sliced Image when using slice_image_ver without .copy() (left) and with (right)


Fig. 3: Sliced Image when using slice_image_hor

1 Like

Solution

When returning a sliced image from Calc Results By Python make sure to use .copy() before returning the image.