智能小车opencv巡线代码
时间: 2023-11-27 16:47:48 浏览: 356
以下是智能小车OpenCV巡线代码的示例:
```python
import cv2
import numpy as np
# 设置ROI区域
def roi(img, vertices):
mask = np.zeros_like(img)
cv2.fillPoly(mask, vertices, 255)
masked = cv2.bitwise_and(img, mask)
return masked
# 处理图像
def process_img(original_image):
# 转换为灰度图像
processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
# 高斯模糊
processed_img = cv2.GaussianBlur(processed_img, (5, 5), 0)
# 边缘检测
processed_img = cv2.Canny(processed_img, threshold1=50, threshold2=150)
# 设置ROI区域
vertices = np.array([[0, 480], [0, 280], [150, 200], [490, 200], [640, 280], [640, 480]], np.int32)
processed_img = roi(processed_img, [vertices])
# 返回处理后的图像
return processed_img
# 找到直线
def find_lines(img, lines):
left_line_x = []
left_line_y = []
right_line_x = []
right_line_y = []
for line in lines:
for x1, y1, x2, y2 in line:
slope = (y2 - y1) / (x2 - x1)
if slope < 0:
left_line_x.extend([x1, x2])
left_line_y.extend([y1, y2])
else:
right_line_x.extend([x1, x2])
right_line_y.extend([y1, y2])
min_y = img.shape[0] * 0.6
max_y = img.shape[0]
poly_left = np.poly1d(np.polyfit(left_line_y, left_line_x, deg=1))
left_x_start = int(poly_left(max_y))
left_x_end = int(poly_left(min_y))
poly_right = np.poly1d(np.polyfit(right_line_y, right_line_x, deg=1))
right_x_start = int(poly_right(max_y))
right_x_end = int(poly_right(min_y))
return [[left_x_start, int(max_y), left_x_end, int(min_y)]], [[right_x_start, int(max_y), right_x_end, int(min_y)]]
# 绘制直线
def draw_lines(img, lines):
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_img, (x1, y1), (x2, y2), [0, 255, 0], thickness=5)
return line_img
# 主函数
def main():
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
processed_img = process_img(frame)
lines = cv2.HoughLinesP(processed_img, rho=6, theta=np.pi / 60, threshold=160, lines=np.array([]), minLineLength=40, maxLineGap=25)
left_line, right_line = find_lines(processed_img, lines)
line_img = draw_lines(frame, [left_line, right_line])
result = cv2.addWeighted(frame, 0.9, line_img, 1, 1)
cv2.imshow("result", result)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
```
阅读全文