Reputation: 71
I have been attempting to count white pixels in an image using this beautiful code found here .
import cv2
image = cv2.imread("pathtoimg", 0)
count = cv2.countNonZero(image)
print(count)
However, this code counts not only the white pixels in the image but also all the pixels that are non strictly black, including very dark colors such as rgb(0,0,1). So the total count exceeeds that of the white pixels count.
So, I am looking for a code that counts only the white pixels rgb(255,255,255)
Any ideas? Thanks so much for your help
Upvotes: 1
Views: 976
Reputation: 995
Since you're looking to match RGB values, in this case only white, the below should do what you want. Note: this solution can be extended to count a range of RGB values by adjusting the lower and upper bounds in the cv2.inRange
function.
import cv2
import numpy as np
image = cv2.imread("pathtoimage")
dst = cv2.inRange(image, np.array([255,255,255], dtype=np.uint8), np.array([255,255,255], dtype=np.uint8))
count = cv2.countNonZero(dst)
print(count)
Upvotes: 1
Reputation: 60
You could try
np.sum(img == 255)
or what you can do is apply filter or reverse colors, so white becomes black and black becomes white then you can simply do it with
gray = cv2.cvtColor("pathtoimg", cv2.COLOR_BGR2GRAY)
pixels = cv2.countNonZero(gray)
Upvotes: 2