【发布时间】:2025-12-08 15:45:01
【问题描述】:
我正在使用 python 代码来分离前景和背景图像,这里解释了 https://*.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% 的像素是黑色的?
【问题讨论】:
-
欢迎来到 *。请阅读并遵循帮助文档中的发布指南。 on topic 和 how to ask 在这里申请。 * 不是设计、编码、研究或教程服务。
-
您发布的代码与您提出的问题无关。你没有表现出任何努力来解决你的问题。我们需要看到这种努力和结果。
标签: python opencv image-processing