Skip to content

Instantly share code, notes, and snippets.

@ankesh007
Last active November 8, 2017 14:55
Show Gist options
  • Save ankesh007/57094337a4cb1d507f603dd89a1f96ec to your computer and use it in GitHub Desktop.
Save ankesh007/57094337a4cb1d507f603dd89a1f96ec to your computer and use it in GitHub Desktop.
import argparse
import cv2
import numpy as np
import matplotlib.pyplot as plt
# import sys
# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False
r=1.0
ref_ht=1790
def click_and_crop(event, x, y, flags, param):
# grab references to the global variables
global refPt, cropping
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
pass
elif event == cv2.EVENT_LBUTTONUP:
refPt.append((x, y))
cropping = False
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow('image', 1000,800)
cv2.setMouseCallback("image", click_and_crop)
# keep looping until the 'q' key is pressed
while True:
cv2.imshow("image", image)
if(len(refPt)==4):
break
key = cv2.waitKey(1) & 0xFF
if len(refPt) == 4:
print refPt
dist=(refPt[0][0]-refPt[1][0])#**2 + (refPt[0][1]-refPt[1][1])**2;
# dist=sqrt(dist)
print dist
pt1=np.asarray(refPt,dtype=np.float32)
refPt[1]=(refPt[0][0]+dist,refPt[0][1])
refPt[2]=(refPt[0][0],refPt[0][1]+dist)
refPt[3]=(refPt[0][0]+dist,refPt[0][1]+dist)
pt2=np.asarray(refPt,dtype=np.float32)
M=cv2.getPerspectiveTransform(pt1,pt2)
dst=cv2.warpPerspective(image,M,(image.shape[0],image.shape[1]))
plt.subplot(121),plt.imshow(image),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
cv2.waitKey(0)
# print pt1.shape
# pt2=np.array([])
# print type(refPt[0][0])
# y_dist=abs(refPt[0][1]-refPt[1][1])
# x_to_estimate=abs(refPt[2][0]-refPt[3][0])
# actual_dist=ref_ht*r
# print (y_dist)
# print (x_to_estimate)
# print (actual_dist/y_dist)*x_to_estimate
else:
print "Didnt receive 4 points"
# close all open windows
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment