python性能提升

时间:2018-12-13 18:56:03

标签: python-3.x performance image-processing

我正在尝试根据以下公式从RGB图像中获取强度值:

我的代码是:

def normalize(image):       #normalize values to between 0 and 1
    image -= image.min()
    image /= image.max()

    image = np.uint8(image * 255)   #convert values to uint8 between 0-255
    return image


def custom_intensity(image):
    h, w, c = image.shape

    intensity = np.zeros((h, w))

    image = image.astype(float)

    for i in range(h):
        for j in range(w):
            divider = image[i, j, 0] + image[i, j, 1] + image[i, j, 2]
            if(divider == 0):
                intensity[i, j] == 0
            else:
                intensity[i, j] = image[i, j, 0] * (image[i, j, 0] / divider) + \
                                  image[i, j, 1] * (image[i, j, 1] / divider) + \
                                  image[i, j, 2] * (image[i, j, 2] / divider)


    intensity = normalize(intensity)
    return intensity

效果不错,但速度较慢。我是python的新手,因此无法进一步改善。如何使此代码更高效?

2 个答案:

答案 0 :(得分:3)

尝试一下:

image += (pow(10, -6), pow(10, -6), pow(10, -6))
intensity = (pow(image[:, :, 0], 2) + pow(image[:, :, 1], 2) + pow(image[:, :, 2], 2)) \
            / (image[:, :, 0] + image[:, :, 1] + image[:, :, 2])

答案 1 :(得分:2)

您不需要成为Python专家。

简化方程式

(R**2 + G**2 + B**2) / (R+G+B)