YOLO11 實例分割模型做行人分割
本文教程將一起學(xué)習(xí)如何利用 YOLO11 分割模型在圖像中準(zhǔn)確隔離和識別人物。
YOLO11 實例分割模型在 Unsplash 圖片上的結(jié)果
引言
實例分割是檢測和隔離圖像中單個對象的關(guān)鍵技術(shù),YOLO11 是執(zhí)行這項任務(wù)的最佳模型之一。在本文中,你將學(xué)習(xí)如何使用 YOLO11 分割模型有效地在圖像中分割人物。我們將涵蓋從設(shè)置 Python 環(huán)境和安裝必要的庫,到下載測試圖像和可視化分割結(jié)果的所有內(nèi)容。通過本教程的學(xué)習(xí),你將清楚地了解如何應(yīng)用 YOLO11 進行準(zhǔn)確的人物分割。
1. 創(chuàng)建 Python 環(huán)境
我們首先將設(shè)置一個 Python 虛擬環(huán)境來管理依賴項。打開你的終端并運行:
python -m venv env
激活虛擬環(huán)境
然后我們需要激活我們的虛擬環(huán)境。根據(jù)你的機器,你可能需要使用不同的命令。這里我展示了在 Windows 和 Mac/Linux 上的兩種方式。Windows:
.\env\Scripts\activate
Mac/Linux:
source env/bin/activate
2. 安裝 Ultralytics 庫
在我們的虛擬環(huán)境激活后,我們需要安裝 ultralytics 庫,這將允許我們使用 YOLO11 實例分割模型。運行以下命令在你的環(huán)境中安裝庫:
pip install ultralytics
3. 下載測試圖像
現(xiàn)在讓我們從 Unsplash 下載一張測試圖像,你可以使用你選擇的任何圖像。我為我們的測試目的選擇了以下圖像:
在 .py 文件中,添加以下代碼來下載圖像:
import cv2
import urllib.request
url, filename = ("https://images.unsplash.com/photo-1484353371297-d8cfd2895020?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8NTUwfHxwZW9wbGV8ZW58MHx8MHx8fDA%3D", "scene.jpg")
urllib.request.urlretrieve(url, filename) # Download the image
# Load the input image using OpenCV
image = cv2.imread(filename)
4. 加載模型并生成推理結(jié)果
下一步是加載我們的分割模型并在測試圖像上運行推理。在本教程中,我們將使用 yolo11n-seg.pt 模型,但你可以使用 Ultralytics YOLO11 文檔中的任何你喜歡的模型。一旦我們的模型加載完畢,我們使用 results = model(filename) 在測試圖像上運行推理,然后創(chuàng)建一個空的分割掩碼。
from ultralytics import YOLO
import numpy as np
# Load the model
model = YOLO("yolo11n-seg.pt") # load an official YOLO model
# Predict with the model
results = model(filename) # predict on an image
# Create an empty mask for segmentation
segmentation_mask = np.zeros_like(image, dtype=np.uint8)
5. 可視化人物分割掩碼
最后一步是可視化我們的模型生成的分割掩碼。YOLO11 模型支持同時分割多個類別,如人物、自行車和汽車等。由于我們只對人物類別感興趣,類別標(biāo)簽為 0,我們只可視化具有此類別的掩碼。在下面的代碼中,我們遍歷結(jié)果并過濾人物掩碼。然后我們將掩碼疊加在圖像上進行清晰的可視化,然后使用 matplotlib 保存并顯示結(jié)果。
# Iterate over the results
for i, r in enumerate(results):
# Iterate through the detected masks
for j, mask in enumerate(r.masks.xy):
# Convert the class tensor to an integer
class_id = int(r.boxes.cls[j].item()) # Extract the class ID as an integer
# Check if the detected class corresponds to 'person' (class ID 0)
if class_id == 0:
# Convert mask coordinates to an integer format for drawing
mask = np.array(mask, dtype=np.int32)
# Fill the segmentation mask with color
cv2.fillPoly(segmentation_mask, [mask], (0, 255, 0))
# Combine the original image with the segmentation mask
segmentation_result = cv2.addWeighted(image, 1, segmentation_mask, 0.7, 0)
# Save the output image with segmentation
cv2.imwrite("output_segmentation.jpg", segmentation_result)
# Optionally display the image (make sure you're running in a GUI environment)
cv2.imshow("Segmentation Result", segmentation_result)
cv2.waitKey(0)
cv2.destroyAllWindows()
如果所有代碼都運行良好,你應(yīng)該得到與下面類似的輸出。這顯然會有所不同,如果你使用了不同的測試圖像。
分割結(jié)果
完整代碼:https://github.com/Brianhulela/yolo11_segmentation