-3

I'm using the python code for separation of foreground from background image explained here https://stackoverflow.com/a/31627979/3490988.

Given this input Image: enter image description here

Running this code:

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)

will result in this image:

enter image description here

In the above image, how can I efficiently extract 10000 random patches(possibly overlapping) of size 64x64 from the foreground such that at most 10% of the pixels in each patch are black?

ahb65
  • 191
  • 2
  • 13
  • 1
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service. – Prune Jul 10 '17 at 22:33
  • 4
    The code you posted has nothing to do with the problem you posed. You have shown no effort to solve your problem. We need to see that effort and the results. – Prune Jul 10 '17 at 22:34

1 Answers1

2
  1. Use numpy.random.randint to generate random pixel coordinates within the image grid. Let this be bottom-left corner of your 64x64 patch. Find the upper-right corner coordinate. NOTE: be careful to adjust limits in numpy.random.randint so that upper-right corner of the patch stays inside the image.

  2. Extract the patch using numpy slicing: img[y1:y2, x1:x2]

  3. 10% of 64x64 is approx. 410. Use one of numpy's functions such as numpy.count_nonzero() to count the number of non-zero elements (number of zeros is 64*64 - nonzeros) and check if the number of zeros is larger or smaller than 410: if it is larger than 410 then black occupies over 10% of pixels and if it is less than 410 then black occupies less than 10%.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45