title: Algorithm - How to distinguish 2 shapes of tray Opencv Python?
body: <p>I have 2 tray images, all I need to do is to detect whether tray is in forward direction,<a href="https://i.stack.imgur.com/TGTd1.jpg" rel="nofollow noreferrer">This is forward direction of tray</a> <a href="https://i.stack.imgur.com/kvqZm.jpg" rel="nofollow noreferrer">This is reverse direction of tray</a> <a href="https://i.stack.imgur.com/mt2Sv.png" rel="nofollow noreferrer">This is the template image</a></p>
  
  <p>First I cropped the source image and get the template image then I used "cv2.matchTemplate" algorithm to get the location of template in source image so <a href="https://i.stack.imgur.com/H9Rc7.png" rel="nofollow noreferrer">This is the result after using cv2.matchTemplate</a> => this is what I want.</p>
  
  <p>But the problem is the head of tray could be deformed like this
  <a href="https://i.stack.imgur.com/rApNT.png" rel="nofollow noreferrer">This is deformed tray</a> (due to operation of machine). If I decrease the threshold value to get both (not deformed and deformed head of tray) the program will also detect the reverse tray instead of forward tray <a href="https://i.stack.imgur.com/v3xu4.png" rel="nofollow noreferrer">This is wrong detect</a> so this is not what I want.</p>
  
  <p>I'm stucking with this, any ideas? Should I change to another method or algorithm?, any helps would be greatly appreciated. </p>
  
  <p>Code I used</p>
  
  <pre><code>import cv2
  import numpy as np
  
  main_image = cv2.imread('forwardtray.jpg')
  gray_image = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY)
  # open the template as gray scale image
  
  template = cv2.imread('tray.png', 0)
  width, height = template.shape[::-1] #get the width and height
  # match the template using cv2.matchTemplate
  match = cv2.matchTemplate(gray_image, template, cv2.TM_CCOEFF_NORMED)
  
  threshold = 0.35
  position = np.where(match &gt;= threshold) # get the location of template in the image
  # draw the rectangle around the matched template
  for point in zip(*position[::-1]): 
  cv2.rectangle(main_image, point, (point[0] + width, point[1] + height), (0, 204, 153), 0)
  cv2.imshow('Template Found', main_image)
  cv2.waitKey(0)
  </code></pre>