如何计算图像中每个矩形中的白色像素?
how to counting white pixels in every rectangle in over image?
我有数千张 1000X2000 像素的图像,我只想计算 100X200 图像的每个小 windows 中的白色像素,并在向量数组中写入计数
请问我如何通过 python openCV 做到这一点?
示例图片:
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);
我有数千张 1000X2000 像素的图像,我只想计算 100X200 图像的每个小 windows 中的白色像素,并在向量数组中写入计数 请问我如何通过 python openCV 做到这一点?
示例图片:
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);