OpenCV를 사용한 간단한 차선 인식 예제

본 포스트에는 OpenCV에서 제공하는 이미지 프로세싱 API들을 사용한 차선 인식하는 Python 예제 코드를 싣고 있다. 


차선인식은 허프 변환(Hough Transform)을 사용하여 도로의 차선을 구분하도록 하였다.

차선 인식을 위해 다음과 같은 이미지 처리과정이 필요하다. 

- 이미지 컬러를 흑백으로 변환

- 노이즈를 제거하기 위한 blurring

- 이미지에서 경계면 검출

- 허프 변환을 통해 이미지에서 선 위치 검출

- 검출된 선 위치데이터를 사용해 차선 필터링


차선 필터링은 간단하게 검출된 선의 각도만을 계산하여 필터링 하였다.


예제 코드는 다음과 같다.

import math
import cv2 as cv

def LaneFiltering(lines):
    
    if lines is None:
        return None
    
    Lanes = []
    
    for i in range(0,len(lines)):
        l = lines[i][0]
        x1,y1,x2,y2 = l[0],l[1],l[2],l[3]
        if x1 == x2:
            Lanes.append([x1,y1,x2,y2])
            continue
        angle = math.atan((y2-y1)/(x2-x1))*180/math.pi
        if abs(angle) > 10:
            Lanes.append([x1,y1,x2,y2])
    
    return Lanes

def SearchLines(img):
    if img is None:
        return None
    
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    gray = cv.GaussianBlur(gray,(7,7),0)
    edges = cv.Canny(gray,40, 100)
    
    cv.imshow('edges',edges)
    
    #Probabilistic Line Transform
    #https://docs.opencv.org/master/dd/d1a/group__imgproc__feature.html#ga8618180a5948286384e3b7ca02f6feeb
    lines = cv.HoughLinesP(edges, 1, math.pi / 180, threshold=80, lines=None, minLineLength=20, maxLineGap=20)
    
    edges = cv.cvtColor(edges,cv.COLOR_GRAY2BGR)
    if lines is not None:
        for i in range(0, len(lines)):
            l = lines[i][0]
            cv.line(edges, (l[0], l[1]), (l[2], l[3]), (255,0,255), 3, cv.LINE_AA)
    
    cv.imshow('HoughLinesP',edges)
    
    return lines
    

def LaneRecognition():
    
    img = cv.imread('road-220058_640.jpg')
    cv.imshow('img',img)
    
    lines = SearchLines(img)
    Lane = LaneFiltering(lines)
        
    if Lane is not None:
        for i in range(0, len(Lane)):
            cv.line(img, (Lane[i][0], Lane[i][1]), (Lane[i][2], Lane[i][3]), (0,255,0), 3, cv.LINE_AA)
    
    cv.imshow('Lane',img)

    cv.waitKey(0)
    cv.destroyAllWindows()


실행 결과는 다음과 같다.



관련 포스트

이미지 blur와 양방향 필터링(Bilateral Filtering)
이미지의 가장자리 경계면 검출 (edge detection) 원리와 예제

댓글

이 블로그의 인기 게시물

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

아두이노(arduino) 심박센서 (heart rate sensor) 심박수 측정 example code

간단한 cfar 알고리즘에 대해

base64 인코딩 디코딩 예제 c 소스

바로 프로젝트 적용 가능한 FIR Filter (low/high/band pass filter )를 c나 python으로 만들기