【发布时间】:2021-10-28 05:23:30
【问题描述】:
我正在尝试使用 numba 加快我对 Floyd-Steinberg's dithering algorithm 的实施。在阅读完初学者指南后,我将@jit 装饰器添加到我的代码中:
def findClosestColour(pixel):
colors = np.array([[255, 255, 255], [255, 0, 0], [0, 0, 255], [255, 255, 0], [0, 128, 0], [253, 134, 18]])
distances = np.sum(np.abs(pixel[:, np.newaxis].T - colors), axis=1)
shortest = np.argmin(distances)
closest_color = colors[shortest]
return closest_color
@jit(nopython=True) # Set "nopython" mode for best performance, equivalent to @njit
def floydDither(img_array):
height, width, _ = img_array.shape
for y in range(0, height-1):
for x in range(1, width-1):
old_pixel = img_array[y, x, :]
new_pixel = findClosestColour(old_pixel)
img_array[y, x, :] = new_pixel
quant_error = new_pixel - old_pixel
img_array[y, x+1, :] = img_array[y, x+1, :] + quant_error * 7/16
img_array[y+1, x-1, :] = img_array[y+1, x-1, :] + quant_error * 3/16
img_array[y+1, x, :] = img_array[y+1, x, :] + quant_error * 5/16
img_array[y+1, x+1, :] = img_array[y+1, x+1, :] + quant_error * 1/16
return img_array
但是,我收到以下错误:
Untyped global name 'findClosestColour': Cannot determine Numba type of <class 'function'>
我想我理解 numba 不知道 findClosestColour 的类型,但我刚刚开始使用 numba,不知道如何处理错误。
这是我用来测试函数的代码:
image = cv2.imread('logo.jpeg')
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
im_out = floydDither(img)
【问题讨论】:
-
您是否尝试将
@jit装饰器也应用于findClosestColour? -
您是否尝试应用 @jit 装饰器并将 nopython 参数设置为 False?
-
@folgerit 我将
@jit装饰器应用到findClosestColour并收到此错误:numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) -
@yannziselman 我尝试将
@jit装饰器参数设置为 false,但我收到了一些弃用警告。与使用普通 python 相比,整体性能没有提高。 -
请提供一个小型可运行的
img_array以供进一步调查。