Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中从前景图像中提取随机面片_Python_Opencv_Image Processing - Fatal编程技术网

在python中从前景图像中提取随机面片

在python中从前景图像中提取随机面片,python,opencv,image-processing,Python,Opencv,Image Processing,我正在使用python代码来分离这里解释的前景和背景图像 给定此输入图像: 运行此代码: 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.findConto

我正在使用python代码来分离这里解释的前景和背景图像

给定此输入图像:

运行此代码:

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%的像素为黑色

用于在图像栅格内生成随机像素坐标。这是64x64修补程序的左下角。找到右上角的坐标。注意:请小心调整numpy.random.randint中的限制,以使面片的右上角保持在图像内

使用numpy切片:img[y1:y2,x1:x2]提取修补程序

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


欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。在这里申请。StackOverflow不是设计、编码、研究或教程服务。您发布的代码与您提出的问题无关。你没有表现出解决问题的努力。我们需要看到这种努力和结果。