yolo를 활용한 segmentation에서 이미 train, val 데이터셋을 구성하고 트레이닝을 완료했어. 이제 이걸로 test dataset을 predict해보려하는데 결과물은 마스크 값들도 나오고, 그냥 이미지에 그 여러 마스크들이 표시되게 하고싶어. 그럴때 코드를 어떻게 짜야해?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
YOLO를 활용한 segmentation(예: YOLOv8-seg, YOLOv5-seg 등)에서 test dataset에 대해 마스크 예측을 하고, 원본 이미지 위에 마스크를 시각화하고 싶으시군요!
아래는 YOLOv8-seg 기준으로 설명드릴게요.
(다른 YOLO segmentation도 거의 비슷합니다.)
1. 모델 로드 및 예측
python
from ultralytics import YOLO
import cv2
import numpy as np
# 모델 로드 (학습한 가중치 경로)
model = YOLO('runs/segment/exp/weights/best.pt')
# 테스트 이미지 경로
img_path = 'test_images/your_test_image.jpg'
# 이미지 불러오기
img = cv2.imread(img_path)
# 예측
results = model(img_path)
2. 마스크 시각화
YOLOv8의 results 객체에서 마스크와 박스, 클래스 정보를 얻을 수 있습니다.
python
# 결과에서 마스크, 박스, 클래스 정보 추출
for result in results:
masks = result.masks.data.cpu().numpy() # (N, H, W)
boxes = result.boxes.xyxy.cpu().numpy() # (N, 4)
classes = result.boxes.cls.cpu().numpy() # (N, )
# 원본 이미지 복사
img_vis = img.copy()
for i, mask in enumerate(masks):
# 마스크를 3채널로 변환
mask_3ch = np.stack([mask]*3, axis=-1)
# 마스크 색상 지정 (랜덤)
color = np.random.randint(0, 255, (1, 3), dtype=np.uint8)
# 마스크를 이미지에 덧씌우기 (알파 블렌딩)
img_vis = np.where(mask_3ch, img_vis*0.5 + color*0.5, img_vis).astype(np.uint8)
# 박스 그리기
x1, y1, x2, y2 = boxes[i].astype(int)
cv2.rectangle(img_vis, (x1, y1), (x2, y2), color.tolist()[0], 2)
# 클래스 이름 표시 (클래스 id를 이름으로 변환 필요시)
cv2.putText(img_vis, str(int(classes[i])), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color.tolist()[0], 2)
# 결과 이미지 저장 또는 표시
cv2.imwrite('test_images/your_test_image_result.jpg', img_vis)
# cv2.imshow('result', img_vis)
# cv2.waitKey(0)
3. 여러 이미지에 대해 반복 적용
여러 test 이미지가 있다면, 위 코드를 반복문으로 감싸면 됩니다.
4. 참고
result.masks.data는 (N, H, W) 형태의 binary mask입니다.
마스크를 컬러로 입히고 싶으면, 각 마스크마다 다른 색상을 지정하면 됩니다.
클래스 이름이 필요하면, 클래스 id를 이름으로 매핑하는 dict를 만들어서 사용하세요.
전체 예시 코드
python
from ultralytics import YOLO
import cv2
import numpy as np
import glob
model = YOLO('runs/segment/exp/weights/best.pt')
test_imgs = glob.glob('test_images/*.jpg')
for img_path in test_imgs:
img = cv2.imread(img_path)
results = model(img_path)
for result in results:
masks = result.masks.data.cpu().numpy()
boxes = result.boxes.xyxy.cpu().numpy()
classes = result.boxes.cls.cpu().numpy()
img_vis = img.copy()
for i, mask in enumerate(masks):
mask_3ch = np.stack([mask]*3, axis=-1)
color = np.random.randint(0, 255, (1, 3), dtype=np.uint8)
img_vis = np.where(mask_3ch, img_vis*0.5 + color*0.5, img_vis).astype(np.uint8)
x1, y1, x2, y2 = boxes[i].astype(int)
cv2.rectangle(img_vis, (x1, y1), (x2, y2), color.tolist()[0], 2)
cv2.putText(img_vis, str(int(classes[i])), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color.tolist()[0], 2)
cv2.imwrite(img_path.replace('.jpg', '_result.jpg'), img_vis)
궁금한 점 있으면 추가로 질문 주세요!
(사용하는 YOLO 버전이나, 원하는 시각화 스타일 등 더 구체적으로 알려주시면 더 맞춤 코드도 드릴 수 있습니다.)
User
자 다시 해볼게!
Training 자체에서 항목을 여러개 학습하다보니 아마 결과에서 mask가 여러개 발견될텐데.
이 mask들을 전부 원본 이미지에 오버레이 시켜서 저장하고싶어.
이때의 코드를 짜줘
Assistant
네! 여러 개의 마스크가 예측된 경우, 모든 마스크를 원본 이미지에 컬러로 오버레이해서 저장하는 코드를 아래에 드릴게요.
아래 코드는 YOLOv8-seg 기준이며,
각 마스크마다 랜덤 컬러를 입혀서 원본 이미지에 반투명하게 오버레이합니다.
전체 코드 예시
python
from ultralytics import YOLO
import cv2
import numpy as np
# 1. 모델 로드
model = YOLO('runs/segment/exp/weights/best.pt')
# 2. 테스트 이미지 불러오기
img_path = 'test_images/your_test_image.jpg'
img = cv2.imread(img_path)
# 3. 예측
results = model(img_path)
# 4. 마스크 오버레이
img_overlay = img.copy()
for result in results:
masks = result.masks.data.cpu().numpy() # (N, H, W)
for i, mask in enumerate(masks):
# 마스크를 0~255로 변환
mask_uint8 = (mask * 255).astype(np.uint8)
# 컬러 랜덤 지정
color = np.random.randint(0, 255, (3,), dtype=np.uint8)
# 컬러 마스크 생성
color_mask = np.zeros_like(img_overlay, dtype=np.uint8)
for c in range(3):
color_mask[:, :, c] = mask_uint8 * color[c] // 255
# 알파 블렌딩 (0.5)
img_overlay = cv2.addWeighted(img_overlay, 1.0, color_mask, 0.5, 0)
# 5. 결과 저장
cv2.imwrite('test_images/your_test_image_overlay.jpg', img_overlay)
여러 이미지에 대해 반복 적용
python
import glob
test_imgs = glob.glob('test_images/*.jpg')
for img_path in test_imgs:
img = cv2.imread(img_path)
results = model(img_path)
img_overlay = img.copy()
for result in results:
masks = result.masks.data.cpu().numpy()
for i, mask in enumerate(masks):
mask_uint8 = (mask * 255).astype(np.uint8)
color = np.random.randint(0, 255, (3,), dtype=np.uint8)
color_mask = np.zeros_like(img_overlay, dtype=np.uint8)
for c in range(3):
color_mask[:, :, c] = mask_uint8 * color[c] // 255
img_overlay = cv2.addWeighted(img_overlay, 1.0, color_mask, 0.5, 0)
save_path = img_path.replace('.jpg', '_overlay.jpg')
cv2.imwrite(save_path, img_overlay)