Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...