python - Calculating number of black pixels per row and column of an image -
i new opencv , python.i want calculate total number of black pixels per row , per column of image.can give hint or help?
as miki suggests, can take advantage of cv2.reduce
.
use
numpy.where
create mask containing1
black pixel was, ,0
other intensity.now call
cv2.reduce
twice (once per axis), performingreduce_sum
, , setting output data type 32 bit integer.
code:
import cv2 import numpy np # make random image img = np.zeros((128,128),np.uint8) cv2.randu(img, 0, 256) mask = np.uint8(np.where(img == 0, 1, 0)) col_counts = cv2.reduce(mask, 0, cv2.reduce_sum, dtype=cv2.cv_32sc1) row_counts = cv2.reduce(mask, 1, cv2.reduce_sum, dtype=cv2.cv_32sc1) print "column counts: ", col_counts.flatten().tolist() print "row counts: ", row_counts.flatten().tolist()
sample output:
column counts: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 1, 1, 1, 0, 2, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 1, 1, 1, 0, 0, 2, 1, 3, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 2, 0, 1, 0, 0, 0, 0, 2, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] row counts: [0, 0, 1, 0, 0, 0, 2, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 2, 0, 0, 0, 1, 1, 2, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 1, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 2]
Comments
Post a Comment