OpenCV 实时识别赛道线并标记黑色赛道中点
要实时识别赛道两边的线并标记灰度处理下黑色赛道中点,你可以按照以下步骤进行操作:
- 导入必要的库和模块:
import cv2
import numpy as np
- 定义函数来处理图像:
def process_image(image):
' 转换为灰度图像 '
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
' 进行灰度阈值处理,将颜色转换为二进制图像 '
ret, binary = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)
' 执行边缘检测 '
edges = cv2.Canny(binary, 50, 150)
' 对边缘图像进行霍夫直线检测 '
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=50)
' 遍历检测到的线条,并画出标记 '
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 3)
' 标记黑色赛道中点 '
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_black = np.array([0, 0, 0])
upper_black = np.array([180, 255, 50])
mask = cv2.inRange(hsv, lower_black, upper_black)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
c = max(contours, key=cv2.contourArea)
M = cv2.moments(c)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
cv2.circle(image, (cx, cy), 5, (0, 0, 255), -1)
return image
- 读取视频流并实时处理:
cap = cv2.VideoCapture(0) ' 或者读取视频文件cap = cv2.VideoCapture('video.mp4') '
while True:
ret, frame = cap.read()
if not ret:
break
processed_frame = process_image(frame)
cv2.imshow('Processed Frame', processed_frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
请注意,这只是一个简单的示例,具体的参数和阈值需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/bUF2 著作权归作者所有。请勿转载和采集!