Calculate the number of "black" pixels in an image (black/white)

Solved
neji55 Posted messages 3 Status Membre -  
 nath84150 -
Hello,
I wrote a Python program that counts the number of "black" pixels from an image (black/white), but unfortunately the counter (“print i”) does not display the result (number of black pixels). Here is my program, where is the problem!

Thank you for your help ^^

1 réponse

Timmydu26 Posted messages 85 Status Membre 30
 
## Indeed, you had initialized your i=0 in your for loops...
## so for each pixel, you reset i to zero every time...
## you need to set it to zero once before the for loops and then
## it increments when necessary.
## Furthermore, your while loop is unnecessary and completely wrong for
## what you want to do here...
## Otherwise, your image is in black and white, so load it in grayscale
## try this instead:

import cv2
import numpy as np

image = cv2.imread('test.jpg',0)
#--> with the zeros, you retrieve an image in grayscale, that is, a single color channel... #so if your image only contained black and white it won't change

somme_px_noir = np.sum(image == 0)
# here, matrix computation is extremely faster than for loops...
print somme_px_noir
# to show you that the result is the same here it is with for loops...
s=0
for i in range(208):
____for j in range(304):
________if image[i,j] == 0:
____________s = s +1
print s
# replace the _ with the same number of spaces
# Best regards.
## If you have any questions, feel free to ask...
8
neji55 Posted messages 3 Status Membre
 
Thank you very much @Timmydu26 for your help, the problem is solved ^^
1
nath84150
 
thank you
1