-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLineTracking.py
65 lines (53 loc) · 1.87 KB
/
LineTracking.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
import numpy as np
import cv2
from controller import Controller
class LineTracking():
#def __init__(self):
# print("Init")
# self.video_capture = cv2.VideoCapture(0)
# self.video_capture.set(3, 160)
# self.video_capture.set(4, 120)
def track_line(self, frame, find):
# Capture the frames
print("Get frame")
#ret, frame = self.video_capture.read()
# Crop the image
if(not find):
crop_img = frame[240:480, 0:640]
else:
crop_img = frame[250:480, 270:370]
# Convert to grayscale
gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
# Gaussian blur
blur = cv2.GaussianBlur(gray,(5,5),0)
# Color thresholding
ret,thresh = cv2.threshold(blur,60,255,cv2.THRESH_BINARY_INV)
# Find the contours of the frame
contours, hierarchy = cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)
# Find the biggest contour (if detected)
if len(contours) > 0:
c = max(contours, key=cv2.contourArea)
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cv2.line(crop_img,(cx,0),(cx,720),(255,0,0),1)
cv2.line(crop_img,(0,cy),(1280,cy),(255,0,0),1)
cv2.drawContours(crop_img, contours, -1, (0,255,0), 1)
if cx >= 100:
print("Turn Right!")
if cx < 100 and cx > 70:
print("On Track!")
if cx <= 70:
print("Turn Left")
print(int(cx))
return int(cx/4)
return -1
if __name__ == "__main__":
cap = cv2.VideoCapture(0)
lt = LineTracking()
#controller = Controller()
while True:
ret, frame = cap.read()
val = lt.track_line(frame, False)
print(val)
#controller.controll(val)