homography2.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import cv2
  2. import numpy as np
  3. import sys
  4. def mouseHandler(event,x,y,flags,param):
  5. global im_temp, pts_dst
  6. if event == cv2.EVENT_LBUTTONDOWN:
  7. cv2.circle(im_temp,(x,y),3,(0,255,255),5,cv2.LINE_AA)
  8. cv2.imshow("Image", im_temp)
  9. if len(pts_dst) < 4:
  10. pts_dst = np.append(pts_dst,[(x,y)],axis=0)
  11. # Read in the image.
  12. im_src = cv2.imread(sys.argv[1])
  13. height, width = im_src.shape[:2]
  14. # Create a list of points.
  15. pts_src = np.empty((0,2),dtype=np.int32)
  16. pts_src = np.append(pts_src, [(0,0)], axis=0)
  17. pts_src = np.append(pts_src, [(width-1,0)], axis=0)
  18. pts_src = np.append(pts_src, [(width-1,height-1)], axis=0)
  19. pts_src = np.append(pts_src, [(0,height-1)], axis=0)
  20. # Destination image
  21. im_dst = cv2.imread(sys.argv[2])
  22. # Create a window
  23. cv2.namedWindow("Image", 1)
  24. im_temp = im_dst
  25. pts_dst = np.empty((0,2),dtype=np.int32)
  26. cv2.setMouseCallback("Image",mouseHandler)
  27. cv2.imshow("Image", im_temp)
  28. cv2.waitKey(0)
  29. tform, status = cv2.findHomography(pts_src, pts_dst)
  30. im_temp = cv2.warpPerspective(im_src, tform,(width,height))
  31. cv2.fillConvexPoly(im_dst, pts_dst, 0, cv2.LINE_AA)
  32. im_dst = im_dst + im_temp
  33. cv2.imshow("Image", im_dst)
  34. cv2.waitKey(0)