title: Ensure ROI crop coordinates (x,y,w,h) are valid and within bounds Python OpenCV
body: <p>Given the <code>(x,y,w,h)</code> coordinates to crop a ROI from an image, how can I ensure that the given coordinates are valid? For example:</p>
  <pre><code>image = cv2.imread('1.jpeg')
  x,y,w,h = 0,0,300,300
  ROI = image[y:y+h,x:x+w]
  cv2.imshow('ROI', ROI)
  cv2.waitKey()
  </code></pre>
  <p>If the <code>(x,y,w,h)</code> coordinates are invalid, it will throw this error:</p>
  <blockquote>
  <p>cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:350: error: (-215:Assertion failed) size.width&gt;0 &amp;&amp; size.height&gt;0 in function 'cv::imshow'</p>
  </blockquote>
  <p>I'm trying to write a function to validate the coordinates before cropping the ROI. Currently, some of my checks are to ensure that:</p>
  <ol>
  <li><code>(x,y,w,h)</code> are all either <code>int</code> or <code>float</code> type</li>
  <li><code>x</code> and <code>y</code> are &gt;= 0</li>
  <li><code>w</code> and <code>h</code> are &gt; 0</li>
  </ol>
  <p>Sometimes it still throws the error, what checks am I missing?</p>
  <p>Example image:</p>
  <img src="https://i.stack.imgur.com/TLkbX.jpg" width="350">
  <p>Code:</p>
  <pre><code>import cv2
  
  def validate_ROI_coordinates(coordinates):
      # (x,y) is top left coordinates
      # Top right corner is is (x + w)
      # Bottom left corner is (y + h) 
      
      x,y,w,h = coordinates
      
      # Ensure its a number, not boolean or string type
      def int_or_float(s):
          try:
              i = int(s)
              return True
          except ValueError:
              try:
                  f = float(s)
                  return True
              except:
                  return False
      
      def within_bounds(x,y,w,h):
          # Ensure that x and y are &gt;= 0
          if x &gt;= 0 and y &gt;= 0:
              # Ensure w and h are &gt; 0 ( can be any positive number)
              if w &gt; 0 and h &gt; 0:
                  return True
          else:
              return False
      
      if all(int_or_float(value) for value in coordinates) and within_bounds(x,y,w,h):
          return True
      else:
          return False
  
  image = cv2.imread('1.jpeg')
  print(image.shape)
  x,y,w,h = 500,0,6600,300
  coordinates = (x,y,w,h)
  
  if validate_ROI_coordinates(coordinates):
      ROI = image[y:y+h,x:x+w]
      cv2.imshow('ROI', ROI)
      cv2.waitKey()
  else:
      print('Invalid ROI coordinates')
  </code></pre>