Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Optimization of mean function of non-zero pixels

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!