Emre dağıstan
Emre dağıstan

Reputation: 301

python performance improvement

I am trying to obtain intensity values from an RGB image based on this formula:

And my code is:

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

Which works well but slow. I am beginner in python so could not improve this further. How can I make this code more efficient?

Upvotes: 2

Views: 61

Answers (2)

otosturop
otosturop

Reputation: 140

Try this:

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])

Upvotes: 4

Nico W.
Nico W.

Reputation: 348

You don't need to be an expert in Python.

Simplify your equation:

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

Upvotes: 2

Related Questions