When I search for a solution of why the code below doesn’t run, I always conclude that it should just work.
I am essentially trying to speed up the colouring of RGB images using numba
. I get that the problem is with setting the item into the brushOverlay
array because if I simply get the item and print it, it works just fine. I thought it could be a static type issue, but all arrays are float64 dtype. What am I missing? Thanks!
from numba import jit
import numpy as np
import matplotlib.pyplot as plt
@jit
def numba_overlay_brush(mask, imgRGB, brushColor):
brushOverlay = imgRGB.copy()
yy, xx = np.nonzero(mask)
for i in range(len(yy)):
for j in range(len(xx)):
for c in range(3):
brushOverlay[i, j, c] = brushColor[c]
return brushOverlay
# Random RGB image with float 0-1
imgRGB = np.random.randint(0, 255, size=(1024, 1024, 3))
imgRGB = imgRGB/255
# Boolean mask where to color the image RGB with red
mask = np.zeros((1024, 1024), bool)
y_center = int(1024/2)
mask[y_center:y_center+2] = True
# Red color
brushColor = np.array([1.0, 0.0, 0.0])
brushOverlay = numba_overlay_brush(mask, imgRGB, brushColor)
Advertisement
Answer
There is an out-of-bound on brushOverlay
which cause a segmentation fault (ie. an unexpected crash of the process due to some part of the memory read/written while it as not been allocated). Indeed, np.nonzero(mask)
returns a tuple of two arrays of size 2048 causing the nested loop to iterate over the range range(2048)
.
Note that Numba does not perform any check on ND-arrays by default (due to the additional overhead it would cause). This is why the error is not explicitly reported.