我正在使用python代码将前景与背景图像分开https://stackoverflow.com/a/31627979/3490988。
运行此代码:
def get_holes(image, thresh):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
im_bw = cv.threshold(gray, thresh, 255, cv.THRESH_BINARY)[1]
im_bw_inv = cv.bitwise_not(im_bw)
contour, _ = cv.findContours(im_bw_inv, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
for cnt in contour:
cv.drawContours(im_bw_inv, [cnt], 0, 255, -1)
nt = cv.bitwise_not(im_bw)
im_bw_inv = cv.bitwise_or(im_bw_inv, nt)
return im_bw_inv
def remove_background(image, thresh, scale_factor=.25, kernel_range=range(1, 15), border=None):
border = border or kernel_range[-1]
holes = get_holes(image, thresh)
small = cv.resize(holes, None, fx=scale_factor, fy=scale_factor)
bordered = cv.copyMakeBorder(small, border, border, border, border, cv.BORDER_CONSTANT)
for i in kernel_range:
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (2*i+1, 2*i+1))
bordered = cv.morphologyEx(bordered, cv.MORPH_CLOSE, kernel)
unbordered = bordered[border: -border, border: -border]
mask = cv.resize(unbordered, (image.shape[1], image.shape[0]))
fg = cv.bitwise_and(image, image, mask=mask)
return fg
img = cv.imread('koAl2.jpg')
nb_img = remove_background(img, 230)
将生成此图片:
在上图中,如何从前景有效地提取10000个大小为64x64的随机色块(可能重叠),使每个色块中至多10%的像素为黑色?
答案 0 :(得分:1)
使用numpy.random.randint
在图像网格中生成随机像素坐标。让它成为64x64补丁的左下角。找到右上角坐标。注意:请小心调整numpy.random.randint
中的限制,以使补丁的右上角保留在图像内。
使用numpy切片提取补丁:img [y1:y2,x1:x2]
64x64的10%是约。 410.使用numpy
之类的numpy.count_nonzero()
函数之一来计算非零元素的数量(零的数量是64 * 64 - 非零)并检查零的数量是否更大或小于410:如果它大于410,则黑色占据10%以上的像素,如果小于410则黑色占据不到10%。