简体   繁体   中英

Faster way to calculate pixel intensity(color value) without iterating through all the pixels in image

I am performing an operation in which I have to calculate sum of all pixel intensity, if the pixel value is >0. Currently, I am iterating through every pixel, which is slower. Can anyone please suggest a faster way to improve my code?

h, w = image.shape[:]
total_intensity = 0
for x in range(h):
    for y in range(w):
        if (image[x][y] > 0):
            total_intensity += image[x][y]

if image is a numpy array you can just do this:

total_intensity = image[image > 0].sum()

if you have a very big image you should worry about overflow issues in the sum, so I strongly suggest to first cast the image

image = np.int64(image)

You can do this:

total_intensity = sum(sum(filter(lambda i: i > 0, image[j])) for j in image)

Where 0 your condition of minimum intensity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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