Counting the No. of Black to White Pixels in the Image Using Opencv

Counting the no. of black to white pixels in the image using OpenCV

colors, counts = np.unique(img.reshape(-1, 3), axis=0, return_counts=True)

for color, count in zip(colors, counts):
print("{} = {} pixels".format(color, count))

[1 1 0] = 6977 pixels
[3 3 3] = 7477 pixels
[6 6 6] = 5343 pixels
[8 8 8] = 4790 pixels
[11 11 11] = 4290 pixels
[13 13 13] = 3681 pixels
[16 16 16] = 3605 pixels
[19 19 19] = 2742 pixels
[21 21 21] = 2984 pixels
[...]

Is it possible to count white pixels only in an image using Python?

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)

how to counting white pixels in every rectangle in over image?

Opencv and Numpy are pretty good at this. You can use numpy slicing to target each box and numpy.sum to count the number of white pixels in the slice.

import cv2
import numpy as np

# count white pixels per box
def boxCount(img, bw, bh):
# declare output list
counts = [];
h, w = img.shape[:2];
for y in range(0, h - bh + 1, bh):
line = [];
for x in range(0, w - bw + 1, bw):
# slice out box
box = img[y:y+bh, x:x+bw];

# count
count = np.sum(box == 255);
line.append(count);
counts.append(line);
return counts;


# load image
img = cv2.imread("jump.png");
img = cv2.resize(img, (1000, 2000));
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);

# define box search params
box_width = 100;
box_height = 200;

# get counts
counts = boxCount(img, box_width, box_height);
for line in counts:
print(line);

Python: find the number of black pixels in images

OpenCV does not offer a function do directly count black pixels but a function to count all pixels that are not black: cv2.countNonZero(img)

As you have not posted your code here is a sample how you could use this:

# get all non black Pixels
cntNotBlack = cv2.countNonZero(img)

# get pixel count of image
height, width, channels = img.shape
cntPixels = height*width

# compute all black pixels
cntBlack = cntPixels - cntNotBlack

Note that this will only find pure black pixel (meaning all channels are exactly zero).

Counting pixels in all distinct regions in an image using OpenCV

connectedComponentsWithStats already gives you area, which is the count of pixels in each component (of non-zero pixels) that can be found in the picture.

a = np.where(np.array(d) < 9, 255, 0).astype(np.uint8)

(nlabels, labels, stats, centroids) = cv.connectedComponentsWithStats(a, connectivity=4)

assert nlabels == 5 # = background + 4 components
print(stats[:, cv.CC_STAT_AREA]) # area: array([15, 14, 3, 9, 9], dtype=int32)

Pay attention to Beaker's comment: CC has a connectivity parameter, which you should set to "4-way".

You should invert your picture, so the black pixels become white. white is non-zero is true and that's always foreground, which is what the CC call expects to work with.

Documentation:
https://docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#gac7099124c0390051c6970a987e7dc5c5

The gaussian blur will turn any binarized image into a soup of grayscale values. Don't apply the gaussian blur, or if you require it, then threshold afterwards. connectedComponents* will threat any non-zero (!) pixel as foreground

counting total pixel numbers of white color in an image

You may adjust the sensitivity like described in this post

For the solution to work better, you can also increase the brightness first:

import numpy as np

frame = cv2.imread('truck.png')

# Incere frame brighness
bright_frame = cv2.add(frame, 50)

# Conver image after appying CLAHE to HSV
hsv_frame = cv2.cvtColor(bright_frame, cv2.COLOR_BGR2HSV)

sensitivity = 70 # Higher value allows wider color range to be considered white color
low_white = np.array([0, 0, 255-sensitivity])
high_white = np.array([255, sensitivity, 255])

white_mask = cv2.inRange(hsv_frame, low_white, high_white)
white = cv2.bitwise_and(frame, frame, mask=white_mask)

cv2.imwrite('white.png', white) #Save out to file (for testing).


# Show result (for testing).
cv2.imshow('white', white)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

enter image description here

Well...

Lots gray pixels on the background are found as white.



Related Topics



Leave a reply



Submit