YOLO Vision 2026:

Ultralytics YOLO를 사용하여 세그멘테이션 객체를 분리하는 방법#

Instance segmentation produces a pixel-precise mask for every detected object, which means you can lift each object out of an image on its own. This guide shows you how to turn Ultralytics YOLO segmentation results into isolated objects using Predict Mode and OpenCV, with either a solid black background or a transparent one for saving as PNG.



Watch: How to Remove Background and Isolate Objects with Ultralytics YOLO Segmentation & OpenCV in Python 🚀

세그멘테이션 객체를 분리하는 이유는 무엇인가요?#

이미지에서 개별 객체를 추출하면 다양한 후속 워크플로가 가능해집니다:

  • 제품 사진, 카탈로그 또는 창의적인 편집을 위한 배경 제거.
  • 감지 결과로부터 분류 데이터셋을 구축하기 위한 객체별 크롭(crop).
  • OCR, 색상 분석 또는 측정과 같은 후속 단계에서 주변 장면이 아닌 객체만 볼 수 있도록 하는 집중 처리.
  • 객체를 새로운 배경에 합성하기 위한 투명 PNG 내보내기.

The recipe works with any Ultralytics YOLO segmentation model and follows four stages: run inferenceextract each contourisolate the objectsave the result.

세그멘테이션 추론 실행#

Install the required libraries, then load a segmentation model (the -seg suffix, required to produce masks) and run prediction on your source image:

from ultralytics import YOLO

# Load a segmentation model
model = YOLO("yolo26n-seg.pt")

# Run inference on a source
results = model.predict(source="path/to/image.jpg")
소스가 없나요? YOLO는 번들로 제공된 샘플 이미지를 사용합니다

If you call model.predict() without a source, Ultralytics falls back to the example images shipped with the package (bus.jpg and zidane.jpg), which is handy for quickly testing the workflow.

객체 윤곽선 추출#

Each item in results corresponds to one image, and iterating over a result yields one detection at a time. For every detection, copy the original image, read the class label, and draw the object's mask contour onto a blank binary mask. The white region of this mask marks exactly which pixels belong to the object.

The snippets in this section and the next run inside the detection loop below; the complete, copy-paste script is in Full Example.

Binary Mask Image{ width="240", align="right" }

from pathlib import Path

import cv2
import numpy as np

for r in results:
    img = np.copy(r.orig_img)
    img_name = Path(r.path).stem  # source image base-name

    # Iterate each detected object in the image
    for ci, c in enumerate(r):
        label = c.names[c.boxes.cls.tolist().pop()]  # class name

        # Build a binary mask and draw the object contour onto it
        b_mask = np.zeros(img.shape[:2], np.uint8)
        contour = c.masks.xy[0].astype(np.int32).reshape(-1, 1, 2)
        cv2.drawContours(b_mask, [contour], -1, (255, 255, 255), cv2.FILLED)
`c.masks.xy[0].astype(np.int32).reshape(-1, 1, 2)`는 무엇을 하나요?
  • c.masks.xy[0] returns the mask contour as (x, y) point coordinates for the object in this single-detection result.
  • .astype(np.int32) converts the points from float32, which OpenCV's drawContours() does not accept.
  • .reshape(-1, 1, 2) reshapes the points into the [N, 1, 2] layout drawContours() expects, where N is the number of contour points.

Passing [contour] with the index -1 draws all points of the supplied contour, and cv2.FILLED fills every enclosed pixel white.

객체 분리#

이진 마스크가 준비되면 이를 원본 이미지와 결합합니다. 배경을 어떻게 설정할지에 따라 두 가지 일반적인 스타일이 있습니다:

분리 스타일 선택

마스크를 3채널로 변환하고 객체와 겹치는 픽셀만 유지합니다. 윤곽선 외부의 모든 것은 검은색이 됩니다:

# Isolate object with a black background
mask3ch = cv2.cvtColor(b_mask, cv2.COLOR_GRAY2BGR)
isolated = cv2.bitwise_and(mask3ch, img)
![Example Full size Isolated Object Image Black Background](https://cdn.jsdelivr.net/gh/ultralytics/assets@main/docs/full-size-isolated-object-black-background.avif){ width=240 }
Full-size object on a black background
바운딩 박스로 크롭

전체 크기 이미지 대신 객체 영역만 유지하려면 감지의 바운딩 박스에 맞춰 슬라이스합니다:

# Bounding box coordinates
x1, y1, x2, y2 = c.boxes.xyxy.cpu().numpy().squeeze().astype(np.int32)
# Crop the isolated image to the object region
iso_crop = isolated[y1:y2, x1:x2]
![Example Crop Isolated Object Image Black Background](https://cdn.jsdelivr.net/gh/ultralytics/assets@main/docs/example-crop-isolated-object-image-black-background.avif){ width=240 }
Object cropped to its bounding box
원본 배경을 포함한 크롭이 필요한가요?

That is built in. Pass save_crop=True to predict() and Ultralytics saves bounding-box crops automatically, no masking required.

결과 저장 (선택 사항)#

분리된 각 객체로 무엇을 할지는 사용자의 결정에 달려 있습니다. 일반적으로 수행되는 다음 단계는 나중에 사용할 수 있도록 디스크에 저장하는 것입니다:

# Save the isolated object to file
cv2.imwrite(f"{img_name}_{label}-{ci}.png", isolated)

Here img_name is the source image stem, label is the class name, and ci is the detection index, so multiple instances of the same class get unique filenames. Swap isolated for iso_crop if you applied the optional crop above.

전체 예제#

The script below combines every step into a single, runnable block. It uses a black background by default; switch the single marked line to np.dstack([img, b_mask]) for a transparent PNG instead:

from pathlib import Path

import cv2
import numpy as np

from ultralytics import YOLO

model = YOLO("yolo26n-seg.pt")
results = model.predict(source="path/to/image.jpg")

for r in results:
    img = np.copy(r.orig_img)
    img_name = Path(r.path).stem

    for ci, c in enumerate(r):
        label = c.names[c.boxes.cls.tolist().pop()]

        # Build a binary mask from the object contour
        b_mask = np.zeros(img.shape[:2], np.uint8)
        contour = c.masks.xy[0].astype(np.int32).reshape(-1, 1, 2)
        cv2.drawContours(b_mask, [contour], -1, (255, 255, 255), cv2.FILLED)

        # Isolate the object (black background)
        mask3ch = cv2.cvtColor(b_mask, cv2.COLOR_GRAY2BGR)
        isolated = cv2.bitwise_and(mask3ch, img)  # transparent PNG: isolated = np.dstack([img, b_mask])

        # Save or add your custom post-processing here
        cv2.imwrite(f"{img_name}_{label}-{ci}.png", isolated)

        # Optional: crop to the bounding box before saving
        # x1, y1, x2, y2 = c.boxes.xyxy.cpu().numpy().squeeze().astype(np.int32)
        # cv2.imwrite(f"{img_name}_{label}-{ci}.png", isolated[y1:y2, x1:x2])

반복적으로 사용하려면 루프 본문을 함수로 래핑하여 여러 이미지에서 호출할 수 있도록 하십시오.

결론#

You now have a complete recipe for isolating segmented objects with Ultralytics YOLO: run inference, build a binary mask from each contour, then extract the object on a black or transparent background and optionally crop it to its bounding box. Explore the full Segment Task and Predict Mode documentation to adapt the workflow to your own classes.

FAQ#

Ultralytics YOLO를 사용하여 세그멘테이션 작업의 객체를 어떻게 분리하나요?#

세그멘테이션 모델을 로드하고, 추론을 실행하고, 각 감지 결과의 윤곽선에서 이진 마스크를 만든 다음 이를 원본 이미지와 결합합니다:

import cv2
import numpy as np

from ultralytics import YOLO

model = YOLO("yolo26n-seg.pt")
results = model.predict(source="path/to/your/image.jpg")

img = np.copy(results[0].orig_img)
b_mask = np.zeros(img.shape[:2], np.uint8)
contour = results[0].masks.xy[0].astype(np.int32).reshape(-1, 1, 2)
cv2.drawContours(b_mask, [contour], -1, (255, 255, 255), cv2.FILLED)

mask3ch = cv2.cvtColor(b_mask, cv2.COLOR_GRAY2BGR)
isolated = cv2.bitwise_and(mask3ch, img)

See the Full Example for the complete per-detection loop.

세그멘테이션 후 분리된 객체를 저장하기 위한 어떤 옵션이 있나요?#

There are two main styles. For a black background, convert the mask to three channels and use cv2.bitwise_and(). For a transparent background (when saving as PNG), stack the mask as a fourth alpha channel with np.dstack([img, b_mask]). Both are shown in Isolate the Object.

분리된 객체를 바운딩 박스로 어떻게 크롭하나요?#

감지 결과에서 바운딩 박스 좌표를 읽어 분리된 이미지를 슬라이스합니다:

x1, y1, x2, y2 = results[0].boxes.xyxy[0].cpu().numpy().astype(np.int32)
iso_crop = isolated[y1:y2, x1:x2]

Learn more about bounding box results in the Predict Mode documentation.

세그멘테이션 작업에서 객체 분리를 위해 Ultralytics YOLO를 사용해야 하는 이유는 무엇인가요?#

Ultralytics YOLO는 정확한 마스크 및 바운딩 박스 생성을 통해 빠르고 실시간인 인스턴스 세그멘테이션을 제공하며, 간단한 Python API를 통해 몇 줄의 OpenCV 코드로 추론 결과를 독립된 객체로 변환할 수 있습니다.

Ultralytics YOLO를 사용하여 배경을 포함한 분리된 객체를 저장할 수 있나요?#

Yes. Use the save_crop argument in predict() to save bounding-box crops with their original background:

results = model.predict(source="path/to/your/image.jpg", save_crop=True)

Read more in the Predict Mode Inference Arguments section.

댓글