차선 감지 -pythonopencv 코드 해독
1 #!D:/Code/python
2 # -*- coding: utf-8 -*-
3 # @Time : 2019/8/29 16:58
4 # @Author : Johnye
5 # @Site :
6 # @File : detect_RoadL.py
7 # @Software: PyCharm
8
9 import cv2 as cv
10 import numpy as np
11 import math
12
13 # LaneLineDetection
14 # ,
15 class LaneLineDetection:
16 def __init__(self):
17 print("instace it")
18 # leftline rightline
19 #
20 self.left_line = {'x1': 0, 'y1': 0, 'x2': 0, 'y2': 0}
21 self.right_line = {'x1': 0, 'y1': 0, 'x2': 0, 'y2': 0}
22
23 def process(self, frame, method=0):
24 #
25 gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
26 # canny
27 binary = cv.Canny(gray, 150, 300)
28 h, w = gray.shape
29 #
30 binary[0:np.int(h/2+40),0:w] = 0
31 #
32 contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
33 #
34 out_image = np.zeros((h, w), frame.dtype)
35 # ,
36 for cnt in range(len(contours)):
37 #
38 p = cv.arcLength(contours[cnt], True)
39 #
40 area = cv.contourArea(contours[cnt])
41 # 、
42 x, y, rw, rh = cv.boundingRect(contours[cnt])
43 if p < 5 or area < 10:
44 continue
45 if y > (h - 50):
46 continue
47 #
48 (x, y), (a, b), angle = cv.minAreaRect(contours[cnt]);
49 angle = abs(angle)
50 # 20 90 90 ,
51 if angle < 20 or angle > 160 or angle == 90.0:
52 continue
53 # contour 5
54 if len(contours[cnt]) > 5:
55 #
56 (x, y), (a, b), degree = cv.fitEllipse(contours[cnt])
57 # 5 160 80 160 ,
58 if degree< 5 or degree>160 or 80:
59 continue
60 # ,
61 cv.drawContours(out_image, contours, cnt, (255), 2, 8)
62 result = self.fitLines(out_image)
63 cv.imshow("contours", out_image)
64 dst = cv.addWeighted(frame, 0.8, result, 0.5, 0)
65 cv.imshow("lane-lines", dst)
66 #
67 def fitLines(self, image):
68 h, w = image.shape
69 h1 = np.int(h / 2 + 40)
70 out = np.zeros((h, w, 3), dtype=np.uint8)
71 cx = w // 2
72 cy = h // 2
73 left_pts = []
74 right_pts = []
75 for col in range(100, cx, 1):
76 for row in range(cy, h, 1):
77 pv = image[row, col]
78 if pv == 255:
79 left_pts.append((col, row))
80 for col in range(cx, w-20, 1):
81 for row in range(cy, h, 1):
82 pv = image[row, col]
83 if pv == 255:
84 right_pts.append((col, row))
85 # 2
86 if len(left_pts) >= 2:
87 [vx, vy, x, y] = cv.fitLine(np.array(left_pts), cv.DIST_L1, 0, 0.01, 0.01)
88 y1 = int((-x * vy / vx) + y)
89 y2 = int(((w - x) * vy / vx) + y)
90 dy = y2 - y1
91 dx = w - 1
92 k = dy/dx
93 c = y1
94
95 w1 = (h1 -c)/k
96 w2 = (h - c) / k
97 cv.line(out, (np.int(w1), np.int(h1)), (np.int(w2), np.int(h)), (0, 0, 255), 8, 8, 0)
98 self.left_line['x1'] = np.int(w1)
99 self.left_line['y1'] = np.int(h1)
100 self.left_line['x2'] = np.int(w2)
101 self.left_line['y2'] = np.int(h)
102 # 1
103 else:
104 x1 = self.left_line['x1']
105 y1 = self.left_line['y1']
106 x2 = self.left_line['x2']
107 y2 = self.left_line['y2']
108 cv.line(out, (x1, y1), (x2, y2), (0, 0, 255), 8, 8, 0)
109 # 2
110 if len(right_pts) >= 2:
111 x1, y1 = right_pts[0]
112 x2, y2 = right_pts[len(right_pts) - 1]
113 dy = y2 - y1
114 dx = x2 - x1
115 k = dy / dx
116 c = y1 - k * x1
117 w1 = (h1 - c) / k
118 w2 = (h - c)/k
119 cv.line(out, (np.int(w1), np.int(h1)), (np.int(w2), np.int(h)), (0, 0, 255), 8, 8, 0)
120 self.right_line['x1'] = np.int(w1)
121 self.right_line['y1'] = np.int(h1)
122 self.right_line['x2'] = np.int(w2)
123 self.right_line['y2'] = np.int(h)
124 # 1
125 else:
126 x1 = self.right_line['x1']
127 y1 = self.right_line['y1']
128 x2 = self.right_line['x2']
129 y2 = self.right_line['y2']
130 cv.line(out, (x1, y1), (x2, y2), (0, 0, 255), 8, 8, 0)
131 return out
132
133
134 def video_run():
135 capture = cv.VideoCapture("images/road_line.mp4")
136 height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
137 width = capture.get(cv.CAP_PROP_FRAME_WIDTH)
138 count = capture.get(cv.CAP_PROP_FRAME_COUNT)
139 fps = capture.get(cv.CAP_PROP_FPS)
140 print(height, width, count, fps)
141 detector = LaneLineDetection()
142 while (True):
143 ret, frame = capture.read()
144 if ret is True:
145 cv.imshow("video-input", frame)
146 detector.process(frame, 0)
147 c = cv.waitKey(1)
148 if c == 27:
149 break
150 else:
151 break
152
153
154 if __name__ == "__main__":
155 video_run()
156 cv.waitKey(0)
157 cv.destroyAllWindows()
전재 대상:https://www.cnblogs.com/codeAndlearn/p/11432366.html
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.