【问题标题】:how to counting white pixels in every rectangle in over image?如何计算图像中每个矩形中的白色像素?
【发布时间】:2021-04-17 10:37:07
【问题描述】:

我有数千张 1000X2000 像素的图像,我想只计算图像 100X200 的每个小窗口中的白色像素,并在向量数组中写入计数 请问如何通过 python openCV 做到这一点?

示例图片:

【问题讨论】:

    标签: numpy opencv image-processing computer-vision image-preprocessing


    【解决方案1】:

    Opencv 和 Numpy 在这方面做得很好。您可以使用 numpy 切片来定位每个框,并使用 numpy.sum 来计算切片中白色像素的数量。

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

    【讨论】:

    • 除了 count = np.sum(box == 255),另一种方法是:count = len(cv2.findNonZero(box)),它适用于“最大白色”和其他色调.
    猜你喜欢
    • 1970-01-01
    • 2020-07-25
    • 2023-03-26
    • 1970-01-01
    • 2020-03-07
    • 2019-03-18
    • 1970-01-01
    • 2012-01-15
    • 2015-02-13
    相关资源
    最近更新 更多