title: Scale contours up/grow outward
body: <p>I have a small script <sup><a href="https://github.com/akinuri/dump/blob/master/python/opencv/scale-contours/show_contours.py" rel="nofollow noreferrer">(GitHub)</a></sup> (based on <a href="https://stackoverflow.com/a/48399309/2202732">this answer</a>) to detect objects on a white background. The script is working fine and detects the objects. For example, this image:</p>
  
  <p><a href="https://i.stack.imgur.com/RDSfu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RDSfu.jpg" alt="original image"></a></p>
  
  <p>becomes this:</p>
  
  <p><a href="https://i.stack.imgur.com/F3rre.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F3rre.jpg" alt="contours on image"></a></p>
  
  <p>and I crop the <code>boundingRect</code> (red one).</p>
  
  <p>I'll be doing further operations on this image. For example instead of a rectangle crop, I will be cropping just the contour. (Anyway, these are further problems to be faced.)</p>
  
  <p>What I want to do, now, is scale up/grow the contour (green one). I'm not sure if scale and grow means the same thing in this context, because when I think of scale, there's usually a single point of origin/anchor point. With grow, it's relative to the edges. I want to have something like this (created in Photoshop): </p>
  
  <p><a href="https://i.stack.imgur.com/Dzsms.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dzsms.jpg" alt="grow example"></a></p>
  
  <p>So after I detect the object/find contours, I want to grow it by some value/ratio, so that I have some space/pixels to modify which won't affect the object. How can I do that?</p>
  
  <p>Mentioned script:</p>
  
  <pre><code># drop an image on this script file
  img_path = Path(sys.argv[1])
  
  # open image with Pillow and convert it to RGB if the image is CMYK
  img = Image.open(str(img_path))
  if img.mode == "CMYK":
      img = ImageCms.profileToProfile(img, "Color Profiles\\USWebCoatedSWOP.icc", "Color Profiles\\sRGB_Color_Space_Profile.icm", outputMode="RGB")
  
  img      = cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
  gray     = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)[1]
  kernel   = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
  morphed  = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
  contours = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
  contour  = sorted(contours, key=cv2.contourArea)[-1]
  
  x, y, w, h = cv2.boundingRect(contour)
  
  final = cv2.drawContours(img, contours, -1, (0,255,0), 2)
  cv2.rectangle(final, (x,y), (x+w,y+h), (0,0,255), 2)
  
  cv2.imshow("final", final)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  </code></pre>
  
  <hr>
  
  <p><sub>Images posted here are scaled down to keep the question short. Original images and the script(s) can be found on the mentioned (first paragraph) GitHub page.</sub></p>