Optimization of mean function of non-zero pixels

asked 2018-12-21 09:11:58 -0500

Laurentiu gravatar image

Hello,

I'm a beginner in OpenCV with python, and I want to compute mean of each channels of image for all pixels != 0

this is my function, but is very slow :(

def meanOfSkin(res):
sum_b = 0
sum_g = 0
sum_r = 0
#remove division by 0
count_b = 0.0000001
count_g = 0.0000001
count_r = 0.0000001
h, w, bpp = np.shape(res)

for py in range(0, h):
    for px in range(0, w):
        if res[py][px][0] != 0:
            sum_b = sum_b + res[py][px][0]
            count_b = count_b + 1
        if res[py][px][1] != 0:
            sum_g = sum_g + res[py][px][1]
            count_g = count_g + 1
        if res[py][px][2] != 0:
            sum_r = sum_r + res[py][px][2]
            count_r = count_r + 1


return int(sum_b / count_b), int(sum_g / count_g), int(sum_r / count_r)

How to optimize my function for a better time and easy method.

Thank you in advance!

edit retag flag offensive close merge delete

Comments

first get a mask using threshold() or compare() functions and then call mean() with mask see sample java code

sturkmen gravatar imagesturkmen ( 2018-12-21 13:01:43 -0500 )edit