简体   繁体   English

更快的图像归一化(numpy 数组)

[英]Faster normalization of image (numpy array)

I've got function that takes some image as a input and changes it values (scales) in a way that average value will be 96 .我有一个函数,可以将一些图像作为输入并以平均值为96的方式更改它的值(比例)。 Here is the function:这是函数:

def normalize_image(image: np.ndarray):
    image_median = np.median(image[image > 0])
    image = image * 96.0 / image_median
    image[image > 255] = 255
    return image

I am using python 3.5.3 and numpy 1.15.2.我正在使用 python 3.5.3 和 numpy 1.15.2。 I profiled my code with cProfile and it turned out that this function takes 6% of all time (in some scenarios up to 25% of all time) having only 50 calls.我用 cProfile 分析了我的代码,结果发现这个函数只需要 6% 的时间(在某些情况下高达 25% 的时间)只有 50 次调用。 These array have shape of (155,256,256).这些数组的形状为 (155,256,256)。

I am not very experienced with optimizing python and I wonder if this could be made faster somehow?我在优化 python 方面不是很有经验,我想知道这是否可以以某种方式做得更快?

Normally I would start with using SIMD optimization but numpy use them heavily already.通常我会从使用 SIMD 优化开始,但 numpy 已经大量使用它们。

There is not much you can do quickly here.在这里,您可以快速完成的事情并不多。

You already use NumPy in a vectorized manner, so internally C code is executed that probably is already quite optimized.您已经以矢量化方式使用 NumPy,因此在内部执行的 C 代码可能已经非常优化。

The calculation of the median can take much longer than calculating the mean (because sorting is involved).中位数的计算可能比计算均值花费的时间长得多(因为涉及排序)。 Consider replacing it.考虑更换它。

Adding some parentheses should save a division of the array添加一些括号应该可以节省数组的除法

image = image * (96.0 / image_median)

because between operators of equal precedence Python goes from left to right.因为在同等优先级的运算符之间 Python 从左到右。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM