-1

I have thousands of images 1000X2000 px and I want count only white pixels in each small windows of image 100X200 and write count number in vector array please how can I do that by python openCV?

Sample Image:

enter image description here

DapperDuck
  • 2,728
  • 1
  • 9
  • 21

1 Answers1

2

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);
Ian Chu
  • 2,924
  • 9
  • 14
  • Besides count = np.sum(box == 255), another way is: count = len(cv2.findNonZero(box)), it will work either for "max white" and for other shades. – Twenkid Jan 12 '21 at 19:06