-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfocalDistance.py
87 lines (63 loc) · 2.1 KB
/
focalDistance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import cv2
import numpy as np
from djitellopy import Tello
drone = Tello()
drone.connect()
drone.streamon()
#Define object specific variables
dist = 0
focal = 450
pixels = 30
width = 5
#find the distance from then camera
def get_dist(rectange_params,image):
#find no of pixels covered
pixels = rectange_params[1][0]
print(pixels)
#calculate distance
dist = (width*focal)/pixels
#Wrtie n the image
image = cv2.putText(image, 'Distance from Camera in CM :', org, font,
1, color, 2, cv2.LINE_AA)
image = cv2.putText(image, str(dist), (110,50), font,
fontScale, color, 1, cv2.LINE_AA)
return image
#Extract Frames
cap = cv2.VideoCapture(0)
#basic constants for opencv Functs
kernel = np.ones((3,3),'uint8')
font = cv2.FONT_HERSHEY_SIMPLEX
org = (0,20)
fontScale = 0.6
color = (0, 0, 255)
thickness = 2
cv2.namedWindow('Object Dist Measure ',cv2.WINDOW_NORMAL)
cv2.resizeWindow('Object Dist Measure ', 700,600)
#loop to capture video frames
while True:
ret, img = cap.read()
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#predefined mask for green colour detection
lower = np.array([40,50,20])
upper = np.array([80, 255, 255])
mask = cv2.inRange(hsv_img, lower, upper)
#Remove Extra garbage from image
d_img = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel,iterations = 5)
#find the histogram
cont,hei = cv2.findContours(d_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cont = sorted(cont, key = cv2.contourArea, reverse = True)[:1]
for cnt in cont:
#check for contour area
if (cv2.contourArea(cnt)>100 and cv2.contourArea(cnt)<306000):
#Draw a rectange on the contour
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box], -1,(255,0,0),3)
img = get_dist(rect,img)
img = drone.get_frame_read().frame
img = cv2.resize(img, (1000, 1000))
cv2.imshow('Object Dist Measure ',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()