> For the complete documentation index, see [llms.txt](https://www.nhasachso.io.vn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.nhasachso.io.vn/truc-tuyen/interactive-blocks-1/tac-gia/nguyen-hong-phuong/sach-cong-cu-ai-python/phan-5-thi-giac-may-tinh-computer-vision/detectron2-framework-manh-me-cho-cac-bai-toan-phan-doan-anh-va-phat-hien-vat-the.md).

# Detectron2: Framework mạnh mẽ cho các bài toán phân đoạn ảnh và phát hiện vật thể

#### **Detectron2**

**Mục tiêu:** Detectron2 là một **framework mã nguồn mở mạnh mẽ** do **Facebook AI Research (FAIR)** phát triển, chuyên dành cho các tác vụ **phân đoạn ảnh, phát hiện vật thể, phân đoạn thể hiện (instance segmentation)** và **pose estimation**.

***

**🚀 Đặc điểm nổi bật:**

* Xây dựng trên **PyTorch**, dễ mở rộng và tùy chỉnh.
* Tích hợp nhiều mô hình tiên tiến như **Faster R-CNN, Mask R-CNN, RetinaNet, DensePose**.
* Hỗ trợ **huấn luyện, đánh giá, và suy luận (inference)** trên tập dữ liệu tùy biến hoặc phổ biến như COCO.
* Hiệu năng cao, phù hợp cho cả nghiên cứu và ứng dụng thực tiễn.

***

**📸 Ứng dụng tiêu biểu:**

* Phát hiện vật thể trong ảnh và video (object detection).
* Phân đoạn đối tượng cụ thể trong ảnh (instance segmentation).
* Phân tích dáng người (pose estimation) trong y tế, thể thao.
* Nhận diện và đếm số lượng vật thể trong chuỗi sản xuất.

***

**🔧 Ví dụ đơn giản: Phát hiện vật thể trong ảnh**

```python
import cv2
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2 import model_zoo
from detectron2.utils.visualizer import Visualizer

# Cấu hình mô hình
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file(
    "COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml"))
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(
    "COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml")
predictor = DefaultPredictor(cfg)

# Dự đoán
image = cv2.imread("coffee_shop.jpg")
outputs = predictor(image)

# Hiển thị kết quả
v = Visualizer(image[:, :, ::-1], scale=1.2)
result = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2.imshow("Detectron2 Result", result.get_image()[:, :, ::-1])
cv2.waitKey(0)
```

***
