title: Mask to filter the area of ​interest (OpenCV)
body: <p>I need a mask to make the circle in this <a href="https://i.stack.imgur.com/J2EDm.png" rel="nofollow noreferrer">image</a> stand out from the background, receiving a binary image, where white is the region of interest (the circle) and black everything else. So I can apply this mask in a video capture, where it is possible to see only the sphere.
  note: the background will generally be white. </p>
  
  <p>I already created codes using the threshold or inRange, with a simple algorithm, that from a selection made by the user manually, marking the region of the circle, it removes the minimum and maximum rgb value, thus creating a parameter to apply in the inRange or threshold. However, as the background is usually white and clear, very similar to the color of the sphere, the binary mask includes the background, making the code a failure.
  Any other method for that?</p>
  
  <pre><code>import cv2
  import numpy as np
  ix,iy = 0,0
  def selection_area(event,x,y,flags,param):
      global ix,iy
      global vx,vy
      if event == cv2.EVENT_LBUTTONDBLCLK:
          cv2.rectangle(img,(x-5,y-5),(x+5,y+5),(255,255,0),-1)
          if ix!=0 and iy!=0:
              cv2.rectangle(img,(x,y),(ix,iy),(255,0,0),1)
              vx=[x,ix]
              vy=[y,iy]
          ix,iy = x,y
  
  def analyzeRGB(cimg):
      b=[];g=[];r=[];
      for j in cimg:
          for i in j:
              b.append(i[0])
              g.append(i[1])
              r.append(i[2])
      lower_blue= np.array([min(b),min(g),min(r)])
      upper_blue= np.array([max(b),max(g),max(r)])
      return lower_blue,upper_blue
  
  
  cap = cv2.VideoCapture(0)
  while(True):
      ret, frame = cap.read()
      cv2.imshow('frame',frame)
      if cv2.waitKey(1) &amp; 0xFF == ord('q'):
          img=frame
          break
  cap.release()
  cv2.destroyAllWindows()
  
  cv2.imshow('Analyze',img)
  
  cv2.setMouseCallback('Analyze',selection_area)
  
  while(1):
      cv2.imshow('Analyze',img)
      k = cv2.waitKey(20) &amp; 0xFF
      if k == ord('q'):
          print (vx,vy)
          break
  cv2.destroyAllWindows()
  cut = img[min(vy)+5:max(vy)-5,min(vx)+5:max(vx)-5]
  
  cv2.imshow("Cut",cut)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  cv2.waitKey(0)
  
  filter_RGB =analyzeRGB(cut)
  img =  cv2.inRange(img, filter_RGB[0],filter_RGB[1])
  
  cv2.imshow("Ready",img)
  cv2.imshow("Cut",cut)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  
  cap = cv2.VideoCapture(0)
  while(True):
      ret, frame = cap.read()
      frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY);
  
      frame =cv2.inRange(frame,filter_RGB[0],filter_RGB[1])
  
      cv2.imshow("Frame",frame)
      if cv2.waitKey(1) &amp; 0xFF == ord('q'):
          break
  cap.release()
  cv2.destroyAllWindows()
  
  </code></pre>