Guest User

Untitled

a guest
Jul 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import sys
  2. import cv2
  3. import numpy as np
  4.  
  5. FULL = "full.jpg"
  6. CROP = "crop.jpg"
  7.  
  8. def template_matching(full, template, start=0.1, stop=1.0, step=0.1):
  9.  
  10. crop_full = cv2.resize(template, tuple(np.roll(full.shape, 1)))
  11.  
  12. best_val = 0
  13. best_scale = 0
  14. best_shape = (0, 0)
  15. best_loc = (0, 0)
  16.  
  17. for s in np.arange(start, stop, step):
  18. tmp = cv2.resize(crop_full, (0, 0), fx=s, fy=s)
  19.  
  20. res = cv2.matchTemplate(full_gray, tmp, cv2.TM_CCOEFF_NORMED)
  21. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
  22.  
  23. #top_left = max_loc
  24. #bottom_right = (top_left[0] + w, top_left[1] + h)
  25. #factor = max_val / (tmp.shape[0]*tmp.shape[1])
  26. print "trying scale ", s, max_val, 1.0/s#, "factor", factor
  27. if max_val > best_val:
  28. best_val = max_val
  29. best_scale = s
  30. best_shape = tmp.shape
  31. best_loc = max_loc
  32.  
  33. #cv2.imshow("image", tmp)
  34. #cv2.imshow("template", cv2.convertScaleAbs(res))
  35. #cv2.waitKey(1)
  36.  
  37. return best_val, best_scale, best_shape, best_loc
  38.  
  39. if __name__ == '__main__':
  40.  
  41. cv2.namedWindow("image", cv2.WINDOW_NORMAL)
  42. cv2.namedWindow("template", cv2.WINDOW_NORMAL)
  43.  
  44. full = cv2.imread(FULL)
  45. crop = cv2.imread(CROP)
  46.  
  47. if crop.shape[0] > full.shape[0] or crop.shape[1] > full.shape[1]:
  48. print "crop is bigger than full image...abort"
  49. print "crop", crop.shape
  50. print "full", full.shape
  51. sys.exit(-1)
  52.  
  53. full_gray = cv2.cvtColor(full, cv2.COLOR_BGR2GRAY)
  54. crop_gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
  55.  
  56.  
  57. best_val, best_scale, best_shape, best_loc = template_matching(full_gray, crop_gray)
  58. # get better result
  59. best_val, best_scale, best_shape, best_loc = template_matching(full_gray, crop_gray,
  60. best_scale-0.15, best_scale+0.15, 0.001)
  61.  
  62. print "upper left corner:", best_loc
  63. print "width, height:", np.roll(best_shape, 1)
  64. print "middlepoint:", (best_loc[0]+best_shape[1]/2, best_loc[1]+best_shape[0]/2)
  65. print "zoom:", 1.0/best_scale
  66. cv2.rectangle(full, best_loc, (best_loc[0]+best_shape[1], best_loc[1]+best_shape[0]), (255, 255, 255), 5)
  67. cv2.imshow("image", full)
  68. cv2.waitKey(0)
Add Comment
Please, Sign In to add comment