title: Python OpenCV Background Subtraction and Bounding Box
body: <p>I am new to using OpenCV and therefore am open to alternative solutions to this problem. I am attempting to obtain the perimeter bounding box of printed circuit boards to crop the ROI from my RGB-D camera to only extract depth data from the region containing the printed circuit board.</p>
  
  <p>Since the camera will be stationary, my initial thought was to use cv2.subtract() using an image of the empty background and an image of a printed circuit board placed on that same background. The output is shown below. </p>
  
  <p>I am now not sure how to obtain the bounding box of the PCB. When I use findContours I obtain 373 different contours which I believe is due to the difference in color of the PCB components, however I only need the perimeter bounding box.</p>
  
  <p>Thanks in advance.
  Jadon<a href="https://i.stack.imgur.com/1KbH6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1KbH6.png" alt="enter image description here"></a></p>
  
  <p>EDIT 1: 
  img1 is background and img2 is the image with the PCB. I believe the main issue is there are so many contours and I am unsure of how to choose the one to create a perimeter bounding box.</p>
  
  <pre><code>diff = cv2.subtract(img1, img2)
  imgray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
  ret, thresh = cv2.threshold(imgray, 127, 255, 0)
  contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, 
  cv2.CHAIN_APPROX_SIMPLE)
  print(len(contours))
  cnt = contours[0]
  
  x,y,w,h = cv2.boundingRect(cnt)
  img = cv2.rectangle(diff, (x,y), (x+w, y+h), (0,255,0),2)
  </code></pre>