[파이썬] 컴퓨터 비전을 활용한 교통 흐름 분석

traffic

컴퓨터 비전은 이미지나 비디오와 같은 시각적 데이터를 처리하고 분석하는 기술입니다. 이 기술을 활용하여 교통 흐름을 분석하면, 도로에서 발생하는 교통 현황 및 문제를 실시간으로 파악할 수 있습니다. 이를 통해 교통 공간을 효율적으로 관리하고, 교통 체증을 예방하거나 출퇴근 시간을 최적화할 수 있습니다.

교통 흐름 분석을 위한 컴퓨터 비전 알고리즘 구현

파이썬은 이미지 및 비디오 처리를 위해 다양한 컴퓨터 비전 라이브러리를 제공합니다. 이중에서도 OpenCV는 가장 많이 사용되는 라이브러리 중 하나입니다. OpenCV를 사용하여 교통 흐름을 분석하는 알고리즘을 구현해보도록 하겠습니다.

단계 1: 비디오 파일 또는 실시간 웹캠 스트림 가져오기

먼저, 교통 흐름을 분석할 동영상 파일을 불러오거나 실시간으로 웹캠 스트림을 가져옵니다. OpenCV를 사용하여 비디오 파일을 열거나 웹캠 장치에 액세스할 수 있습니다.

import cv2

# 비디오 파일 열기
video = cv2.VideoCapture("traffic_video.mp4")

# 또는 웹캠 장치에 액세스
video = cv2.VideoCapture(0)  # 0은 첫 번째 장치를 의미합니다

단계 2: 차선 검출

교통 흐름 분석에서 중요한 부분은 차선을 검출하는 것입니다. 차선 검출은 교통 흐름의 방향과 주행 영역을 파악하는 데 도움이 됩니다. OpenCV의 이미지 처리 기능과 컴퓨터 비전 알고리즘을 활용하여 차선을 검출할 수 있습니다.

def detect_lane(image):
    # 이미지 전처리

    # 효과적인 경계 검출을 위해 그레이 스케일로 변환
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 가우시안 블러를 적용하여 이미지를 부드럽게 만듦
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 엣지 검출을 위해 캐니 알고리즘 적용
    edges = cv2.Canny(blurred, 50, 150)

    # 관심 영역 설정

    # 교통 영역 관심 영역의 꼭지점 좌표
    height, width = image.shape[:2]
    roi_vertices = [(0, height), (width // 2, height // 2), (width, height)]

    # 마스크 생성
    mask = np.zeros_like(edges)
    cv2.fillPoly(mask, np.array([roi_vertices], dtype=np.int32), 255)

    # 관심 영역 적용
    masked_edges = cv2.bitwise_and(edges, mask)

    # 차선 검출 알고리즘

    # 허프 변환을 이용한 직선 검출
    lines = cv2.HoughLinesP(masked_edges, rho=2, theta=np.pi/180, threshold=100, minLineLength=100, maxLineGap=50)

    # 검출된 차선 시각화
    lane_image = np.zeros_like(image)
    draw_lines(lane_image, lines)

    return lane_image

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

단계 3: 차량 및 보행자 감지

교통 흐름 분석은 차량이나 보행자의 움직임 또한 파악해야 합니다. 이를 위해 객체 감지 알고리즘을 사용할 수 있습니다. 대표적인 객체 감지 알고리즘 중 하나인 YOLO (You Only Look Once)를 활용해보겠습니다.

def detect_objects(image):
    # YOLO 모델 로드
    net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")

    # 클래스 이름 로드
    with open("coco.names", "r") as f:
        classes = [line.strip() for line in f.readlines()]

    # 이미지 전처리 및 객체 감지 수행
    blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
    net.setInput(blob)
    layer_names = net.getLayerNames()
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    outputs = net.forward(output_layers)

    # 객체 감지 결과 시각화
    confidence_threshold = 0.5
    for output in outputs:
        for detection in output:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > confidence_threshold:
                center_x = int(detection[0] * image.shape[1])
                center_y = int(detection[1] * image.shape[0])
                width = int(detection[2] * image.shape[1])
                height = int(detection[3] * image.shape[0])
                x = int(center_x - width / 2)
                y = int(center_y - height / 2)

                cv2.rectangle(image, (x, y), (x+width, y+height), (0, 255, 0), 2)
                cv2.putText(image, classes[class_id], (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

    return image

단계 4: 결과 시각화

마지막으로, 객체 감지와 차선 검출을 결합하여 최종 결과를 시각화합니다. 결과 이미지에는 검출된 차선과 객체, 그리고 추가적인 정보가 포함될 수 있습니다.

while True:
    ret, frame = video.read()
    if not ret:
        break

    lane_image = detect_lane(frame)
    objects_image = detect_objects(frame)

    result_image = cv2.addWeighted(lane_image, 0.8, objects_image, 0.2, 0)

    cv2.imshow("Traffic Analysis", result_image)

    if cv2.waitKey(1) == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

결론

컴퓨터 비전을 활용한 교통 흐름 분석은 도로에서 발생하는 교통 현황과 문제를 실시간으로 파악하기 위한 강력한 도구입니다. 이를 통해 교통 체증 예방, 효율적인 교통 관리, 그리고 출퇴근 시간의 최적화를 할 수 있습니다. Python과 OpenCV의 조합을 사용하여 교통 흐름 분석 알고리즘을 구현하는 방법을 살펴보았습니다. 이를 응용하여 실제 도로에서의 교통 상황 분석을 수행할 수 있습니다.