【问题标题】:Extract random patches from foreground image in python [closed]从python中的前景图像中提取随机补丁[关闭]
【发布时间】: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 topichow to ask 在这里申请。 * 不是设计、编码、研究或教程服务。
  • 您发布的代码与您提出的问题无关。你没有表现出任何努力来解决你的问题。我们需要看到这种努力和结果。

标签: python opencv image-processing


【解决方案1】:
  1. 使用numpy.random.randint 在图像网格内生成随机像素坐标。让它成为 64x64 补丁的左下角。找到右上角的坐标。注意:请注意调整numpy.random.randint 中的限制,以使补丁的右上角保持在图像内。

  2. 使用 numpy 切片提取补丁:img[y1:y2, x1:x2]

  3. 64x64 的 10% 约为。 410.使用numpy的函数之一如numpy.count_nonzero()统计非零元素的数量(零的数量为64*64 - 非零)并检查零的数量是否大于或小于410:如果大于 410 则黑色占据 10% 以上的像素,如果小于 410 则黑色占据不到 10%。

【讨论】:

    最近更新 更多