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.

  1. use numpy.where create mask containing 1 black pixel was, , 0 other intensity.

  2. now call cv2.reduce twice (once per axis), performing reduce_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

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -