본문 바로가기
포트폴리오/딥러닝 프로젝트

Building Detection_YOLOv11 Segementation

by 유스베리이 2025. 1. 23.

TODO

UAM에서  위치 파악을 위해 Yolov11 segmentation 모델을 활용하여 Object detection으로 Building Segmentation

 

 

Dataset

Yolov11-seg model을 직접 custom data로 train 시키기 위해 위성 영상 dataset을 ai 허브에서 다운 받아서 사용

https://www.aihub.or.kr/aihubdata/data/view.do?currMenu=&topMenu=&aihubDataSe=data&dataSetSn=73

 

AI-Hub

샘플 데이터 ? ※샘플데이터는 데이터의 이해를 돕기 위해 별도로 가공하여 제공하는 정보로써 원본 데이터와 차이가 있을 수 있으며, 데이터에 따라서 민감한 정보는 일부 마스킹(*) 처리가 되

www.aihub.or.kr

 

 

 

데이터 구조

  • 관심객체 검출: 객체의 길이, 방향을 알 수 있는 회전된 형태의 바운딩 박스(rotated bounding box)를 지도 좌표와 함께 geojson 형태로 제공
    - 위치 박스: [중심좌표 x, y, 박스크기 H, W, 회전각 θ]
  • 건물윤곽 추출: 다각형의 건물 윤곽과 종류를 지도 좌표와 함께 geojson 형태로 제공
    - 위치 모양: polygon 형태의 닫힌 도형
  • 도로 추출: 도로 윤곽과 종류를 지도 좌표와 함께 geojson 형태로 제공
    - 위치 모양: polygon 형태의 닫힌 도형

 

Data Annotation

https://docs.ultralytics.com/ko/datasets/segment/#ultralytics-yolo-format

 

인스턴스 세분화 데이터 세트 개요

Ultralytics YOLO 에서 지원되는 데이터 세트 형식을 살펴보고 개체 세분화 모델 학습을 위한 데이터 세트 준비 및 사용 방법을 알아보세요.

docs.ultralytics.com

원천 데이터 :.jpg

라벨링 데이터 : .json   -> Box형태가 아닌 polygon 형식

polygon json -format-> .txt 파일로 변환

 

txt 파일 구성 

<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn> 로 format 을 해야한다.

 

ex) 

45 0.782016 0.986521 0.937078 0.874167 0.957297 0.782021 0.950562 0.739333 0.825844 0.561792 0.714609 0.420229 0.657297 0.391021 0.608422 0.4 0.0303438 0.750562 0.0016875 0.811229 0.003375 0.889896 0.0320156 0.986521
45 0.557859 0.143813 0.487078 0.0314583 0.859547 0.00897917 0.985953 0.130333 0.984266 0.184271 0.930344 0.386521 0.80225 0.480896 0.763484 0.485396 0.684266 0.39775 0.670781 0.3955 0.679219 0.310104 0.642141 0.253937 0.561234 0.155063 0.559547 0.137083
50 0.39 0.727063 0.418234 0.649417 0.455297 0.614125 0.476469 0.614125 0.51 0.590583 0.54 0.569417 0.575297 0.562354 0.601766 0.56 0.607062 0.536479 0.614125 0.522354 0.637063 0.501167 0.665297 0.48 0.69 0.477646 0.698828 0.494125 0.698828 0.534125 0.712938 0.529417 0.742938 0.548229 0.760594 0.564708 0.774703 0.550583 0.778234 0.536479 0.781766 0.531771 0.792359 0.541167 0.802937 0.555292 0.802937 0.569417 0.802937 0.576479 0.822359 0.576479 0.822359 0.597646 0.811766 0.607062 0.811766 0.618833 0.818828 0.637646 0.820594 0.656479 0.827641 0.687063 0.827641 0.703521 0.829406 0.727063 0.838234 0.708229 0.852359 0.729417 0.868234 0.750583 0.871766 0.792938 0.877063 0.821167 0.884125 0.861167 0.817062 0.92 0.734125 0.976479 0.711172 0.988229 0.48 0.988229 0.494125 0.967063 0.517062 0.912937 0.508234 0.832937 0.485297 0.788229 0.471172 0.774125 0.395297 0.729417
45 0.375219 0.0678333 0.375219 0.0590833 0.386828 0.0503542 0.424156 0.0315208 0.440797 0.0281458 0.464 0.0389167 0.525531 0.115583 0.611797 0.222521 0.676359 0.306583 0.678875 0.317354 0.677359 0.385271 0.66475 0.394687 0.588594 0.407458 0.417094 0.517771 0.280906 0.604521 0.0806562 0.722208 0.0256719 0.763917 0.00296875 0.809646 0 0.786104 0 0.745083 0 0.612583 0.03525 0.613271 0.0877187 0.626708 0.130594 0.626708 0.170437 0.6025 0.273844 0.548708 0.338906 0.507 0.509906 0.4115 0.604734 0.359042 0.596156 0.338188 0.595141 0.306583 0.595141 0.291792 0.579516 0.213104 0.516969 0.129042 0.498297 0.100792 0.466516 0.0987708 0.448875 0.0786042 0.405484 0.0705208 0.375219 0.0678333 0.28675 0.108375 0.282719 0.123167 0.267078 0.162854 0.266062 0.189083 0.245391 0.199833 0.203516 0.251625 0.187375 0.269771 0.159641 0.240188 0.101125 0.249604 0 0.287271 0 0.250271 0 0.245563 0.0975938 0.202521 0.203516 0.145354 0.251953 0.123167 0.28675 0.108375
49 0.587812 0.128229 0.612281 0.0965625 0.663391 0.0840833 0.690031 0.0908125 0.700109 0.10425 0.705859 0.133042 0.700109 0.143604 0.686422 0.146479 0.664828 0.153188 0.644672 0.157042 0.629563 0.175271 0.605797 0.181021 0.595 0.147437
49 0.7405 0.178417 0.733719 0.173896 0.727781 0.162583 0.729484 0.150167 0.738812 0.124146 0.747281 0.0981458 0.776109 0.0811875 0.804094 0.0845833 0.814266 0.102667 0.818516 0.115104 0.812578 0.133208 0.782906 0.151292 0.754063 0.172771
49 0.602656 0.178854 0.636125 0.167875 0.655172 0.165125 0.6665 0.162375 0.680391 0.155521 0.691719 0.153458 0.703047 0.154146 0.713859 0.162375 0.724156 0.174729 0.730844 0.193271 0.733422 0.217979 0.733938 0.244063 0.733422 0.281813 0.732391 0.295542 0.728266 0.300354 0.702016 0.294854 0.682969 0.28525 0.672156 0.270146
49 0.716891 0.0519583 0.683766 0.0103958 0.611688 0.0051875 0.568828 0.116875 0.590266 0.15325 0.590266 0.116875 0.613641 0.0857083 0.631172 0.0857083 0.6565 0.083125 0.679875 0.0883125 0.691563 0.0961042 0.711031 0.0649375

 

annotation을 위한 format 코드 작성

import json
import os
import cv2

# JSON 및 이미지/라벨 디렉토리 경로
json_dir = "/home/validation/labels"
image_dir = "/home/validation/images"  # 원본 이미지가 있는 폴더
output_dir = "/home/labels/val"


os.makedirs(output_dir, exist_ok=True)


for filename in os.listdir(json_dir):
    if filename.endswith(".json"):
        json_path = os.path.join(json_dir, filename)
        txt_filename = os.path.splitext(filename)[0] + ".txt"
        output_txt_path = os.path.join(output_dir, txt_filename)

        
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

    
        image_filename = os.path.splitext(filename)[0] + ".png"
        image_path = os.path.join(image_dir, image_filename)

        if not os.path.exists(image_path):
           
            continue

        image = cv2.imread(image_path)
        img_height, img_width = image.shape[:2] 

        objs = []
        for feature in data.get("features", []):
            if "building_imcoords" in feature.get("properties", {}):
                coords = feature["properties"]["building_imcoords"]
                if coords and coords != "EMPTY":
                    coords_list = list(map(float, coords.split(',')))

                  
                    norm_coords = []
                    for i in range(0, len(coords_list), 2):
                        x = max(0, min(coords_list[i] / img_width, 1))  
                        y = max(0, min(coords_list[i + 1] / img_height, 1))
                        norm_coords.append(f"{x:.6f} {y:.6f}")

                   
                    yolo_format = f"0 {' '.join(norm_coords)}"
                    objs.append(yolo_format)

       
        if objs:
            with open(output_txt_path, 'w', encoding='utf-8') as f:
                for obj in objs:
                    f.write(obj + "\n")

 

YAML 파일 작성

 

building 만 detection 하기 위해 class 0 하나밖에 없다.

path: ../datasets/building
train: images/train  # 학습 데이터 경로
val: images/val  # 검증 데이터 경로
 # 클래스 개수 (건물 1개)
names: 
  0: building  # 클래스 인덱스는 0부터 시작해야 함

 

Train 과 Validation dataset을 준비한다

 

Train

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-seg.pt")   # load a pretrained model (recommended for training)

# Train the model
model.train(data="building.yaml" , epochs= 100, imgsz=640)

 

Validation

from ultralytics import YOLO

# Load a model

model = YOLO("/home/weights/best.pt")

# Validate the model
metrics = model.val()  # no arguments needed, dataset and settings remembered
metrics.box.map  # map50-95(B)
metrics.box.map50  # map50(B)
metrics.box.map75  # map75(B)
metrics.box.maps  # a list contains map50-95(B) of each category
metrics.seg.map  # map50-95(M)
metrics.seg.map50  # map50(M)
metrics.seg.map75  # map75(M)
metrics.seg.maps  # a list contains map50-95(M) of each category

Train

Result

 

Prediction

from ultralytics import YOLO

# Load a model
#model = YOLO("/home/yolo11n-seg.pt") 
model = YOLO("/homeweights/best.pt")

# Predict with the model
results = model("/home/prediction_img.png",save=True, show=True, show_boxes = False, line_width = 1) # predict on an image

 

prediction parameter를 수정해 원하는 prediction 이미지 구조로 수정

yolov11 공식 문서 참고