用此代码写一下实验步骤(对特定名词进行解释)
时间: 2024-12-09 13:28:48 浏览: 13
### 实验步骤及名词解释
#### 1. 准备工作
- **安装依赖库**:确保已安装 `numpy`, `opencv-python`, 和 `pyserial` 库。可以通过以下命令安装:
```bash
pip install numpy opencv-python pyserial
```
- **连接设备**:确保摄像头和串口设备已经正确连接,并且摄像头能够正常工作。串口设备的端口号需要与代码中的设置一致(如 `/dev/ttyUSB0`)。
#### 2. 代码解析
- **导入库**:
```python
import time
import numpy as np
import cv2
from enum import Enum
import math
import serial
import struct
```
这些库分别用于时间控制、数学计算、图像处理、枚举类型定义、串口通信等。
- **定义状态枚举**:
```python
class State(Enum):
none = 0
left = 1
right = 2
center = 3
left_to_center = 4
right_to_center = 5
```
枚举类型 `State` 用于表示车辆的不同状态,如左偏、右偏、居中等。
- **定义处理图像的类 `Bike_class`**:
```python
class Bike_class:
def __init__(self):
# 初始化各种参数和变量
...
```
类 `Bike_class` 包含了图像处理的各种方法和属性,如透视变换矩阵、图像尺寸、状态变量等。
- **初始化方法 `__init__`**:
```python
def __init__(self):
self.M = None
self.M_inverse = None
self.M_inverse_list = None
self.get_warp_M()
self.img_size = (640, 480)
self.img = None
self.warp_img = None
self.edges = None
self.state = State.center
self.blue_state = State.none
self.margin = 30
self.minpix = 50
self.left_lane_inds = []
self.last_good_left_inds_len = 0
self.right_lane_inds = []
self.last_good_right_inds_len = 0
self.nwindows = 8
self.window_height = np.int32(self.img_size[1] / self.nwindows)
self.nonzero = None
self.nonzeroy = None
self.nonzerox = None
self.leftx_mean = None
self.rightx_mean = None
self.left_fit = None
self.right_fit = None
self.lane_center_x = None
self.angle = 0.0
self.deviation = 0.0
self.ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
self.frame_header = b'\x02\x03'
self.frame_tail = b'\x04\x05'
```
初始化方法中设置了各种参数和变量,并初始化了串口通信。
- **获取透视变换矩阵 `get_warp_M`**:
```python
def get_warp_M(self):
objdx = 200
objdy = 230
imgdx = 220
imgdy = 250
list_pst = [[172, 330], [461, 330], [75, 475], [546, 475]]
pts1 = np.float32(list_pst)
pts2 = np.float32([[imgdx, imgdy], [imgdx + objdx, imgdy], [imgdx, imgdy + objdy], [imgdx + objdx, imgdy + objdy]])
self.M = cv2.getPerspectiveTransform(pts1, pts2)
self.M_inverse = cv2.getPerspectiveTransform(pts2, pts1)
self.M_inverse_list = self.M_inverse.flatten()
```
该方法计算并保存透视变换矩阵及其逆矩阵,用于将图像从一种视角转换到另一种视角。
- **图像预处理 `img_preprocess`**:
```python
def img_preprocess(self):
if self.img is None:
return
self.img = cv2.GaussianBlur(self.img, (5, 5), 0)
self.img = self.apply_clahe(self.img)
self.warp_img = cv2.warpPerspective(self.img, self.M, self.img_size)
edges = cv2.Canny(self.warp_img, 50, 150, apertureSize=3)
kernel = np.ones((3, 3), np.uint8)
edges = cv2.dilate(edges, kernel, iterations=2)
edges_mask = np.zeros((self.img_size[1], self.img_size[0]), dtype=np.uint8)
cv2.rectangle(edges_mask, (160, 0), (480, 480), 255, thickness=cv2.FILLED)
self.edges = cv2.bitwise_and(edges, edges, mask=edges_mask)
```
该方法对图像进行高斯模糊、自适应直方图均衡化、透视变换、Canny边缘检测等预处理操作。
- **检测车道线 `detect_lane_lines`**:
```python
def detect_lane_lines(self):
if self.edges is None:
return
self.nonzero = self.edges.nonzero()
self.nonzeroy = np.array(self.nonzero[0])
self.nonzerox = np.array(self.nonzero[1])
histogram = np.sum(self.edges[self.edges.shape[0] // 2:, :], axis=0)
midpoint = int(histogram.shape[0] / 2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
leftx_current = leftx_base
rightx_current = rightx_base
self.left_lane_inds = []
self.right_lane_inds = []
for window in range(self.nwindows):
win_y_low = self.img_size[1] - (window + 1) * self.window_height
win_y_high = self.img_size[1] - window * self.window_height
win_xleft_low = leftx_current - self.margin
win_xleft_high = leftx_current + self.margin
good_left_inds = ((self.nonzeroy >= win_y_low) & (self.nonzeroy < win_y_high) & (self.nonzerox >= win_xleft_low) & (self.nonzerox < win_xleft_high)).nonzero()[0]
self.left_lane_inds.append(good_left_inds)
if len(good_left_inds) > self.minpix:
leftx_current = np.int32(np.mean(self.nonzerox[good_left_inds]))
win_xright_low = rightx_current - self.margin
win_xright_high = rightx_current + self.margin
good_right_inds = ((self.nonzeroy >= win_y_low) & (self.nonzeroy < win_y_high) & (self.nonzerox >= win_xright_low) & (self.nonzerox < win_xright_high)).nonzero()[0]
self.right_lane_inds.append(good_right_inds)
if len(good_right_inds) > self.minpix:
rightx_current = np.int32(np.mean(self.nonzerox[good_right_inds]))
self.left_lane_inds = np.concatenate(self.left_lane_inds)
self.right_lane_inds = np.concatenate(self.right_lane_inds)
if len(self.left_lane_inds) > self.minpix and len(self.right_lane_inds) > self.minpix:
leftx = self.nonzerox[self.left_lane_inds]
lefty = self.nonzeroy[self.left_lane_inds]
rightx = self.nonzerox[self.right_lane_inds]
righty = self.nonzeroy[self.right_lane_inds]
self.left_fit = np.polyfit(lefty, leftx, 2)
self.right_fit = np.polyfit(righty, rightx, 2)
ploty = np.linspace(0, self.img_size[1] - 1, self.img_size[1])
left_fitx = self.left_fit[0] * ploty ** 2 + self.left_fit[1] * ploty + self.left_fit[2]
right_fitx = self.right_fit[0] * ploty ** 2 + self.right_fit[1] * ploty + self.right_fit[2]
self.lane_center_x = (left_fitx[-1] + right_fitx[-1]) / 2
```
该方法通过滑动窗口技术检测车道线,并拟合多项式曲线。
- **确定车辆状态 `bike_determine_state`**:
```python
def bike_determine_state(self):
if self.left_fit is None or self.right_fit is None:
print("车道线未检测到,无法确定状态。")
return
if -55 <= self.deviation < -45:
self.state = State.left
elif -45 <= self.deviation < -15:
self.state = State.left_to_center
elif -15 <= self.deviation < 15:
self.state = State.center
elif 15 <= self.deviation < 45:
self.state = State.right_to_center
elif 45 <= self.deviation <= 55:
self.state = State.right
else:
self.state = State.center
print(f"车辆状态:{self.state.name}")
```
该方法根据车道线的偏差确定车辆的状态。
- **发送数据到串口 `send_data_via_serial`**:
```python
def send_data_via_serial(self, angle, deviation, state_value, blue_state):
data = f"{angle:.2f},{deviation:.2f},{state_value},{blue_state}"
frame = self.frame_header + data.encode() + self.frame_tail
self.ser.write(frame)
```
该方法将车辆的状态、角度和偏差等数据通过串口发送出去。
- **主程序入口**:
```python
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
bike = Bike_class()
while True:
ret, frame = cap.read()
if ret:
bike.img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
bike.img_preprocess()
bike.detect_lane_lines()
bike.bike_determine_state()
blue_object_coords = bike.detect_blue_object(frame)
if blue_object_coords:
x, y, w, h = blue_object_coords
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
print(f"Blue object detected at: ({x}, {y}), width: {w}, height: {h}, State: {bike.blue_state}")
else:
print("No blue object detected.")
bike.send_data_via_serial(bike.angle, bike.deviation, bike.state.value, bike.blue_state)
bike.draw_center_line()
bike.calculate_steering_angle()
bike.img_windows()
else:
print("错误:未找到图像。")
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
```
主程序中打开摄像头,创建 `Bike_class` 实例,进入主循环读取摄像头图像,进行图像处理、车道线检测、状态判断、蓝色彩球检测等操作,并显示结果图像。
#### 3. 运行实验
- **运行代码**:
```bash
python your_script_name.py
```
运行脚本后,摄像头会开始捕捉图像,并实时处理显示结果。
- **观察结果**:
- 观察图像窗口,查看车道线检测、车辆状态判断、蓝色彩球检测等结果。
- 查看串口输出的数据,确认数据传输是否正常。
#### 4. 结束实验
- **按 Esc 键结束程序**:
按下 Esc 键后,程序会释放摄像头资源并关闭所有 OpenCV 创建的窗口。
### 名词解释
- **透视变换**:将图像从一种视角转换到另一种视角的技术,常用于将道路图像转换为俯视图。
- **滑动窗口**:一种逐层搜索车道线的方法,通过在图像中划分多个窗口来检测车道线的位置。
- **多项式拟合**:通过多项式函数拟合车道线的形状,以便更准确地描述车道线。
- **Canny 边缘检测**:一种常用的边缘检测算法,用于提取图像中的边缘信息。
- **高斯模糊**:通过卷积核对图像进行模糊处理,减少噪声。
- **直方图均衡化**:增强图像对比度的一种方法,通过调整图像的直方图分布。
- **串口通信**:通过串口设备进行数据传输,常用于嵌入式系统或硬件控制。
希望这些步骤和解释对你有所帮助!如果有任何问题,请随时提问。
阅读全文