以下是使用OpenCV实时识别赛道两边的线并找出在结果画面显示中分屏并在灰度处理下拟合显示黑色赛道中心位置的示例代码:

import cv2
import numpy as np

def region_of_interest(img, vertices):
    mask = np.zeros_like(img)
    cv2.fillPoly(mask, vertices, 255)
    masked_img = cv2.bitwise_and(img, mask)
    return masked_img

def draw_lines(img, lines, color=(0, 255, 0), thickness=3):
    for line in lines:
        for x1, y1, x2, y2 in line:
            cv2.line(img, (x1, y1), (x2, y2), color, thickness)

def process_image(frame):
    # Convert image to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Apply Gaussian blur
    blur = cv2.GaussianBlur(gray, (5, 5), 0)

    # Apply Canny edge detection
    edges = cv2.Canny(blur, 50, 150)

    # Define region of interest
    height = frame.shape[0]
    width = frame.shape[1]
    vertices = np.array([[(0, height), (width // 2, height // 2), (width, height)]], dtype=np.int32)
    roi = region_of_interest(edges, vertices)

    # Apply Hough line transformation
    lines = cv2.HoughLinesP(roi, 1, np.pi/180, 100, minLineLength=100, maxLineGap=50)

    # Draw detected lines on image
    line_img = np.zeros((height, width, 3), dtype=np.uint8)
    draw_lines(line_img, lines)

    # Split the image into left and right halves
    left_img = line_img[:, :width // 2, :]
    right_img = line_img[:, width // 2:, :]

    # Convert left image to grayscale
    left_gray = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY)

    # Apply thresholding to detect black pixels
    _, left_thresh = cv2.threshold(left_gray, 1, 255, cv2.THRESH_BINARY)

    # Fit a line to the black pixels in left image
    left_pixels = np.transpose(np.nonzero(left_thresh))
    left_line = cv2.fitLine(left_pixels, cv2.DIST_L2, 0, 0.01, 0.01)

    # Calculate center position of left line
    left_center_x = int(left_line[2])
    left_center_y = int(left_line[3])

    # Draw center position on left image
    cv2.circle(left_img, (left_center_x, left_center_y), 5, (0, 0, 255), -1)

    # Display the processed images
    cv2.imshow('Original', frame)
    cv2.imshow('Line Detection', line_img)
    cv2.imshow('Left Half', left_img)

    # Show the center position
    print('Left Line Center:', left_center_x, left_center_y)

    # Press 'q' to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()

# Initialize video capture
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    process_image(frame)

在此示例中,我们首先定义了一些辅助函数。region_of_interest函数用于提取图像的感兴趣区域,draw_lines函数用于在图像上绘制检测到的直线。

process_image函数是主要的图像处理函数。它首先将输入帧转换为灰度图像,并对其应用高斯模糊和Canny边缘检测。然后,它定义了感兴趣区域,并在该区域上应用霍夫线变换来检测直线。接下来,它将检测到的直线绘制在一个新的图像上,并将图像分为左右两半。然后,它将左侧图像转换为灰度图像,并应用阈值处理来检测黑色像素。最后,它使用cv2.fitLine函数将黑色像素拟合为一条直线,并计算出黑色赛道的中心位置。然后,它在左侧图像上绘制中心位置,并显示原始图像、检测到的直线图像和左侧图像。

您可以根据需要更改参数和调整图像处理步骤来适应您的应用场景。

OpenCV 实时赛道识别与中心位置拟合

原文地址: https://www.cveoy.top/t/topic/bT8t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录