-
Notifications
You must be signed in to change notification settings - Fork 2
/
nyc_lane_detection.py
86 lines (58 loc) · 1.95 KB
/
nyc_lane_detection.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
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Define ROI
def roi(image, vertices):
mask = np.zeros_like(image)
mask_color = 255
cv2.fillPoly(mask, vertices, mask_color)
masked_img = cv2.bitwise_and(image, mask)
return masked_img
# Draw Hough Lines on image
def draw_lines(lines, image):
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
return image
def process(img):
try:
# Define roi vertices
h, w, _ = img.shape
roi_vertices = [
(200, h),
(w/2, 2*h/3),
(w-100, h)
]
# Convert to GRAYSCALE
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply dilation (morphology)
kernel = np.ones((3, 3), np.uint8)
gray_img = cv2.dilate(gray_img, kernel=kernel)
# Canny edge detection
canny = cv2.Canny(gray_img, 60, 255)
# ROI
roi_image = roi(canny, np.array([roi_vertices], np.int32))
# Hough Lines
hough_lines = cv2.HoughLinesP(roi_image, 1, np.pi / 180, 40, minLineLength=10, maxLineGap=5)
final_img = draw_lines(hough_lines, img)
return final_img
except Exception:
return img
cap = cv2.VideoCapture("./Data/Manhattan_Trim.mp4")
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*"XVID")
saved_frame = cv2.VideoWriter("Manhattan_detection.avi", fourcc, 30.0, (frame_width, frame_height))
while cap.isOpened():
_, frame = cap.read()
try:
frame = process(frame)
saved_frame.write(frame)
cv2.imshow("final", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
except Exception:
break
cap.release()
saved_frame.release()
cv2.destroyAllWindows()