Skip to content
Search

MMDetection

lastmod 2026-07-07created 2021-10-1447 edits

OpenMMLab Detection Toolbox and Benchmark

MMDetection is a kind of platform that implements various well-known models for object detection and instance segmentation in a single toolbox.

The developers say they hope many people use it to apply existing detection models to various fields and to help create new models.

Categories

Features

  • Modular design: models are modularized, so building your own is easy.
  • Supported Framwork: uniquely supports multiple frameworks.
  • High efficiency: all box and mask operations run on the GPU. Training is faster than on other platforms such as Detectron(facebook), maskrcnn-benchmark, and SimpleDet.
  • State of the art: built on the code of the MMDet team, which won the 2018 COCO Detection Challenge.

Supported Framworks

Models included in MMDetection.

  • Single-state Method
  • Two-state Methods
  • Multi-state Methods
    • Cascade R-CNN
    • Hybrid Task Cascade - The model with the highest performance
  • General Modules and Methods
    • Mixed Precision Training
    • Soft NMS
    • OHEM
    • DCN
    • DCNv2
    • Train from Scratch
    • ScratchDet
    • M2Det - 2018, a new feature pyramid network for building more efficient feature pyramids
    • GCNet
    • Generalized Attention
    • SyncBN
    • Group Normalization
    • Weight Standardization
    • HRNet - 2019, a new backbone focused on training with high-resolution images.
    • Guided Anchoring
    • Libra R-CNN

How to install

As of 2021-10-20, the installed versions are as follows:

Installing CUDA

Ubuntu 18.04:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.4.2/local_installers/cuda-repo-ubuntu1804-11-4-local_11.4.2-470.57.02-1_amd64.deb
sudo dpkg -i cuda-repo-ubuntu1804-11-4-local_11.4.2-470.57.02-1_amd64.deb
sudo apt-key add /var/cuda-repo-ubuntu1804-11-4-local/7fa2af80.pub
sudo apt-get update
sudo apt-get -y install cuda

Ubuntu 20.04:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.4.2/local_installers/cuda-repo-ubuntu2004-11-4-local_11.4.2-470.57.02-1_amd64.deb
sudo dpkg -i cuda-repo-ubuntu2004-11-4-local_11.4.2-470.57.02-1_amd64.deb
sudo apt-key add /var/cuda-repo-ubuntu2004-11-4-local/7fa2af80.pub
sudo apt-get update
sudo apt-get -y install cuda

Reboot after installation

Installing PyTorch

How to install PyTorch 1.8.2 with PIP:

WARNING

PyTorch 1.9.1 is not supported by MMDetection, so I installed 1.8.2.

CUDA 11.1:

pip3 install torch==1.8.2+cu111 torchvision==0.9.2+cu111 torchaudio==0.8.2 -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html

CUDA 10.2:

pip3 install torch==1.8.2+cu102 torchvision==0.9.2+cu102 torchaudio==0.8.2 -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html

Installing mmcv

As of 2021-10-20, version 1.3.15 is available under the following conditions.

  • PyTorch 1.3.0 ~ 1.8.0
  • CUDA 10.1, 10.2, 11.1
  • Python 3.6, 3.7, 3.8

MMDetection 2.17.0 is compatible with mmcv-full>=1.3.8, <1.4.0.

You must get the full version, not the lite version. Enter it in the following format.

pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/{cu_version}/{torch_version}/index.html

CUDA 11.1, PyTorch 1.8.0:

opy -m pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.8.0/index.html

CUDA 10.2, PyTorch 1.8.0:

opy -m pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu102/torch1.8.0/index.html

See the https://download.openmmlab.com/mmcv/dist/ page for the package list.

Installing MMDetection

pip install mmdet

As of 2021-10-20, version 2.17.0 was installed.

[Optional] Extra dependencies are as follows

Install extra dependencies for Instaboost, Panoptic Segmentation, LVIS dataset, or Albumentations.

# for instaboost
pip install instaboostfast
# for panoptic segmentation
pip install git+https://github.com/cocodataset/panopticapi.git
# for LVIS dataset
pip install git+https://github.com/lvis-dataset/lvis-api.git
# for albumentations
pip install albumentations>=0.3.2 --no-binary imgaug,albumentations

Installing with MIM

Install mim for easy installation of OpenMMLab Packages.

Proceed after setting up the venv space with the opy script:

mkdir test
cd test
cp {나의 opy python 단독 스크립트} ./python

## CUDA 12.2 에서 테스트진행
./python -m pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu121
./python -m pip install -U openmim
./python -m mim install mmengine

./python -m mim install "mmcv>=2.0.0"
## 만약 mmdet 3.3.0 을 설치할 예정이라면 `mmcv<2.2.0,>=2.0.0rc4` 조건이 걸려있다. 다음과 같이 설치해야 한다.
./python -m mim install "mmcv==2.1.0"

Note that in MMCV-v2.x, mmcv-full was renamed to mmcv. To install mmcv without CUDA ops, you can install the lite version with mim install "mmcv-lite>=2.0.0rc1".

Installing directly from the mmdet source code

git clone https://github.com/open-mmlab/mmdetection.git
cd mmdetection
pip install -v -e .
# "-v" means verbose, or more output
# "-e" means installing a project in editable mode,
# thus any local modifications made to the code will take effect without reinstallation.

Installing with mim

If you want to install mmdet as a dependency, as a third-party package

./python -m mim install mmdet

If you get the error mmdet 3.3.0 requires mmcv<2.2.0,>=2.0.0rc4; extra == "mim", but you have mmcv 2.2.0 which is incompatible., install mmcv==2.1.0.

See the https://pypi.org/project/mmcv/#history page for the version history of mmcv.

Build dockerfile

ARG PYTORCH="2.4.0"
ARG CUDA="12.4"
ARG CUDNN="9"

FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-runtime as builder

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc g++

WORKDIR /app
COPY . .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/.wheels -r requirements.docker.txt && \
    pip wheel --no-cache-dir --no-deps --wheel-dir /app/.wheels "openmim>=0.3.9" && \
    python setup.py bdist_wheel && \
    cp dist/*.whl /app/.wheels

# --[[ NEXT STAGE
FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-runtime

WORKDIR /app
COPY --from=builder /app/.wheels /app/.wheels
RUN apt-get update && \
    apt-get install -y --no-install-recommends libgl1-mesa-dev gcc g++ ffmpeg tk vim && \
    pip install --no-cache /app/.wheels/* && \
    mim install "mmengine==0.10.4" && \
    mim install "mmcv==2.1.0" && \
    mim install "mmdet==3.3.0" && \
    rm -rf /app/.wheels && \
    addgroup --gid 1001 --system app && \
    adduser --no-create-home \
        --shell /bin/false \
        --disabled-password \
        --uid 1001 \
        --system \
        --group app
USER app

ENTRYPOINT ["python", "-OO", "-m", "ddrm"]

Import the custom module

If we customize a module and register it into the corresponding registry, could we directly build it from the configuration file as the previous section does? The answer is “I don’t know” since I’m not sure the registration process has been triggered. To solve this “unknown” case, Config provides the custom_imports function, to make sure your module could be registered as expected.

For example, we customize an optimizer:

from mmengine.registry import OPTIMIZERS

@OPTIMIZERS.register_module()
class CustomOptim:
    pass

CocoDataset Example

# -*- coding: utf-8 -*-

from mmdet.datasets.coco import CocoDataset
from mmdet.registry import DATASETS


@DATASETS.register_module()
class PlateCocoDataset(CocoDataset):
    """Dataset for COCO"""

    METAINFO = {
        "classes": ("Plate",),
        # palette is a list of color tuples, which is used for visualization.
        "palette": [
            (106, 0, 228),
        ],
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._metainfo["dataset_type"] = None

XMLDataset Example

# -*- coding: utf-8 -*-

from mmdet.datasets.xml_style import XMLDataset
from mmdet.registry import DATASETS


@DATASETS.register_module()
class SeahVOCDataset(XMLDataset):
    """Dataset for PASCAL VOC."""

    METAINFO = {
        "classes": ("Bloom", "Ingot", "Billet", "Slab", "Rod", "Forklift", "Support"),
        # palette is a list of color tuples, which is used for visualization.
        "palette": [
            (106, 0, 228),
            (119, 11, 32),
            (165, 42, 42),
            (0, 0, 192),
            (197, 226, 255),
            (0, 60, 100),
            (0, 0, 142),
        ],
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._metainfo["dataset_type"] = None

demo/image_demo.py

See MMDetection:ImageDemo.

Includes how to run demo/image_demo.py from the command line.

demo/video_demo.py

See MMDetection:VideoDemo.

Includes how to run demo/video_demo.py from the command line.

Simple Example

# -*- coding: utf-8 -*-

import os
from datetime import datetime
from glob import glob
from pathlib import Path
from sys import exit as sys_exit
from typing import List, Tuple, Union

import cv2
from mmdet.apis import init_detector, inference_detector
from mmdet.datasets.coco import CocoDataset
from mmdet.registry import DATASETS, VISUALIZERS
from mmdet.structures.det_data_sample import DetDataSample
from numpy import uint8, ndarray
from numpy.typing import NDArray

NumberType = Union[int, float]


@DATASETS.register_module()
class PlateCocoDataset(CocoDataset):
    """Dataset for COCO"""

    METAINFO = {
        "classes": ("Plate",),
        # palette is a list of color tuples, which is used for visualization.
        "palette": [
            (106, 0, 228),
        ],
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._metainfo["dataset_type"] = None


class ObjectSample:
    def __init__(
        self,
        index: int,
        label: str,
        score: float,
        x1: NumberType,
        y1: NumberType,
        x2: NumberType,
        y2: NumberType,
        color: Tuple[int, int, int],
    ):
        self.index = index
        self.label = label
        self.score = score
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.color = color

def convert_det_to_obj(classes: List[str], palette: List[Tuple[int, int, int]], sample: DetDataSample) -> List[ObjectSample]:
    result = list()
    pred = sample.pred_instances.numpy()
    for i in range(len(pred)):
        x1, y1, x2, y2 = pred.bboxes[i].tolist()  # noqa
        label_index = pred.labels[i].tolist()  # noqa
        label_name = classes[label_index]
        color = palette[label_index]
        score = pred.scores[i].tolist()  # noqa
        obj = ObjectSample(label_index, label_name, score, x1, y1, x2, y2, color)
        result.append(obj)
    return result

def visualize(visualizer, score_threshold: float, image: NDArray[uint8], data_sample: DetDataSample) -> NDArray[uint8]:
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    visualizer.add_datasample(
        name="Preview",
        image=rgb_image,
        data_sample=data_sample,
        draw_gt=False,
        pred_score_thr=score_threshold,
        show=False,
    )
    visualized_image = visualizer.get_image()
    return cv2.cvtColor(visualized_image, cv2.COLOR_RGB2BGR)

def main() -> None:
    config_file = "./rtmdet-ins_x_8xb16-300e_coco_dongkuk_rolling_plate_cam1_2nd.py"
    checkpoint_file = "./epoch_300.pth"
    model = init_detector(config_file, checkpoint_file, device="cuda:0")  # or device="cpu"

    files = glob("./input/*.jpg")
    files.sort()

    output_dir = Path("output")
    if not output_dir.is_dir():
        output_dir.mkdir()

    visualizer = VISUALIZERS.build(model.cfg.visualizer)
    visualizer.dataset_meta = model.dataset_meta

    for filename in files:
        frame = cv2.imread(filename)

        begin = datetime.now()
        result = inference_detector(model, frame)
        assert isinstance(result, DetDataSample)
        duration = (datetime.now() - begin).total_seconds()
        print(f"Predict duration: {duration:.04f}s")

        # print(result)

        begin = datetime.now()
        try:
            visualized_image = visualize(visualizer, 0.5, frame, result)
        except BaseException as e:
            print(f"Visualizer error: {e}")
            continue
        duration = (datetime.now() - begin).total_seconds()
        print(f"Visualizer duration: {duration:.04f}s")

        file_prefix, ext = os.path.splitext(os.path.basename(filename))
        output_filename = file_prefix + ".png"
        output_filepath = str(output_dir / output_filename)
        print(output_filepath)
        cv2.imwrite(output_filepath, visualized_image)

        classes = visualizer.dataset_meta["classes"]
        palette = visualizer.dataset_meta["palette"]
        objs = convert_det_to_obj(classes, palette, result)
        # print(objs)

if __name__ == "__main__":
    sys_exit(main())

MMDetModel Example

The Sample and ModelInterface classes are omitted. If you want to see them, see:

# -*- coding: utf-8 -*-

from os import path
from typing import Any, List, Optional, Sequence, Tuple

from cvlayer.cv.cvt_color import CvtColorCode, cvt_color
from mmdet.apis import inference_detector, init_detector  # noqa
from mmdet.registry import VISUALIZERS  # noqa
from mmdet.structures.det_data_sample import DetDataSample  # noqa
from numpy import uint8, zeros
from numpy.typing import NDArray
from overrides import override

from ddrm.arguments import DEFAULT_DEVICE, DEFAULT_SCORE_THRESHOLD
from ddrm.models.interface import ModelInterface
from ddrm.models.mmdet.datasets.plate_coco import PlateCocoDataset  # noqa
from ddrm.models.sample import Sample


class MMDetModel(ModelInterface):
    def __init__(
        self,
        config: str,
        checkpoint: str,
        device=DEFAULT_DEVICE,
        threshold=DEFAULT_SCORE_THRESHOLD,
        ignore_labels: Optional[Sequence[str]] = None,
        extra: Optional[str] = None,
        name: Optional[str] = None,
    ):
        if not path.isfile(config):
            raise FileNotFoundError(f"Config file not found: '{config}'")
        if not path.isfile(checkpoint):
            raise FileNotFoundError(f"Checkpoint file not found: '{checkpoint}'")

        self._model = init_detector(config, checkpoint, device=device)
        self._ignore_labels = ignore_labels
        self._extra = extra if extra else str()
        self._name = name if name else type(self).__class__.__name__
        self._visualizer = VISUALIZERS.build(self._model.cfg.visualizer)
        self._threshold = threshold

        # the dataset_meta is loaded from the checkpoint and
        # then pass to the model in init_detector
        self._visualizer.dataset_meta = self._model.dataset_meta

    @property
    def name(self) -> str:
        return self._name

    @property
    def threshold(self) -> float:
        return self._threshold

    @property
    def classes(self) -> List[str]:
        return self._visualizer.dataset_meta["classes"]

    @property
    def palette(self) -> List[Tuple[int, int, int]]:
        return self._visualizer.dataset_meta["palette"]

    def convert_det_to_samples(self, det: DetDataSample) -> List[Sample]:
        result = list()
        pred = det.pred_instances.numpy()
        for i in range(len(pred)):
            label_index = pred.labels[i].tolist()  # noqa
            label_name = self.classes[label_index]
            if self._ignore_labels and label_name in self._ignore_labels:
                continue
            x1, y1, x2, y2 = pred.bboxes[i].tolist()  # noqa
            score = pred.scores[i].tolist()  # noqa
            color = self.palette[label_index]
            mask = zeros(pred.masks[i].shape, dtype=uint8)  # noqa
            mask[pred.masks[i]] = 255
            sample = Sample(label_index, label_name, score, x1, y1, x2, y2, color, mask)
            result.append(sample)
        return result

    def inference(self, image: NDArray) -> DetDataSample:
        return inference_detector(self._model, image)

    def visualize(self, image: NDArray, det: DetDataSample) -> NDArray:
        self._visualizer.add_datasample(
            name=self._name,
            image=cvt_color(image, CvtColorCode.BGR2RGB),
            data_sample=det,
            draw_gt=False,
            pred_score_thr=self._threshold,
            show=False,
        )
        return cvt_color(self._visualizer.get_image(), CvtColorCode.RGB2BGR)

    @override
    def get_extra(self) -> Any:
        return self._extra

    @override
    def set_extra(self, extra: Any) -> None:
        self._extra = extra

    @override
    def inference_raw(self, image: NDArray, **kwargs):
        return self.inference(image)

    @override
    def inference_samples(self, image: NDArray, **kwargs) -> List[Sample]:
        return self.convert_det_to_samples(self.inference_raw(image, **kwargs))

    @override
    def run(
        self,
        image: NDArray,
        preview: Optional[NDArray] = None,
        **kwargs,
    ) -> Tuple[List[Sample], Optional[NDArray]]:
        det = self.inference(image)
        samples = self.convert_det_to_samples(det)
        visualized = self.visualize(preview if preview is not None else image, det)
        return samples, visualized

Troubleshooting

unexpected key in source state_dict: data_preprocessor.mean, data_preprocessor.std

The training result (*.pth file) has unused keys. Just ignore it.

dependency conflicts

Install the following pytorch requirements on Python 3.11.4:

--index-url https://download.pytorch.org/whl/cu124
torch==2.4.0+cu124
torchvision==0.19.0+cu124
torchaudio==2.4.0+cu124

Then run the following bash script for mmdet:

#!/usr/bin/env bash

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)

"$ROOT_DIR/python" -m pip install "openmim>=0.3.9"
"$ROOT_DIR/python" -m mim install "mmengine>=0.10.3"
"$ROOT_DIR/python" -m mim install "mmcls>=0.25.0"
"$ROOT_DIR/python" -m mim install "mmdet>=3.3.0"
"$ROOT_DIR/python" -m mim install "mmcv>=2.1.0"

# "$ROOT_DIR/python" -m mim install "mmcv-full>=1.7.2"  # Error

The following error occurred during installation:

ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
mmdet 3.3.0 requires mmcv<2.2.0,>=2.0.0rc4; extra == "mim", but you have mmcv 2.2.0 which is incompatible.

Korean translation:

오류: pip의 종속성 리졸버는 현재 설치된 모든 패키지를 고려하지 않습니다. 이 동작은 다음 종속성 충돌의 원인입니다.
mmdet 3.3.0에는 mmcv<2.2.0,>=2.0.0rc4; extra == "mim"이 필요하지만 호환되지 않는 mmcv 2.2.0이 있습니다.

In conclusion, reinstall mmcv to match the mmcv<2.2.0,>=2.0.0rc4 condition. For reference, the latest version matching this condition is 2.1.0, uploaded on October 17, 2023.

./python -m pip uninstall mmcv
./python -m pip install mmcv==2.1.0

See also the #AssertionError: MMCV==1.7.2 is used but incompatible. Please install mmcv>=2.0.0rc4, <2.2.0 section below.

=== AssertionError: MMCV==1.7.2 is used but incompatible. Please install mmcv>=2.0.0rc4, <2.2.0 === Ran it and got an error...

/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmcv/__init__.py:20: UserWarning: On January 1, 2023, MMCV will release v2.0.0, in which it will remove components related to the training process and add a data transformation module. In addition, it will rename the package names mmcv to mmcv-lite and mmcv-full to mmcv. See https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md for more details.
  warnings.warn(
Traceback (most recent call last):
  File "/home/user/Projects/rtmdet/./sample.py", line 9, in <module>
    from mmdet.apis import init_detector, inference_detector
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/__init__.py", line 17, in <module>
    and mmcv_version < digit_version(mmcv_maximum_version)), \
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: MMCV==1.7.2 is used but incompatible. Please install mmcv>=2.0.0rc4, <2.2.0.

Let's check the mmcv info:

./python -m pip show mmcv

The output is as follows:

Name: mmcv
Version: 2.1.0
Summary: OpenMMLab Computer Vision Foundation
Home-page: https://github.com/open-mmlab/mmcv
Author: MMCV Contributors
Author-email: [email protected]
License:
Location: /home/user/Project/ddrm/.venv/lib/python3.11/site-packages
Requires: addict, mmengine, numpy, opencv-python, packaging, Pillow, pyyaml, yapf
Required-by:

I wondered why this was happening... let's read it carefully:

/home/user/Project/ddrm/.venv/lib/python3.11/site-packages/mmcv/__init__.py:20: UserWarning: On January 1, 2023, MMCV will release v2.0.0, in which it will remove components related to the training process and add a data transformation module. In addition, it will rename the package names mmcv to mmcv-lite and mmcv-full to mmcv. See https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md for more details.

The problem was that mmcv-full was installed. The mmcv-full version was 1.7.2...

Removing mmcv-full and installing mmcv made it work

How to force it to run

Tested on an NVIDIA GeForce RTX 4090, but the #ModuleNotFoundError: No module named 'mmcv._ext' issue occurred and kept repeating...

If you just want to force it to run as a workaround, remove the version check Assertion in mmcv/__init__.py.

ModuleNotFoundError: No module named 'mmcv._ext'

Full Traceback:

Traceback (most recent call last):
  File "/home/user/Projects/rtmdet/./sample.py", line 9, in <module>
    from mmdet.apis import init_detector, inference_detector
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/apis/__init__.py", line 2, in <module>
    from .det_inferencer import DetInferencer
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/apis/det_inferencer.py", line 22, in <module>
    from mmdet.evaluation import INSTANCE_OFFSET
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/evaluation/__init__.py", line 4, in <module>
    from .metrics import *  # noqa: F401,F403
    ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/evaluation/metrics/__init__.py", line 5, in <module>
    from .coco_metric import CocoMetric
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/evaluation/metrics/coco_metric.py", line 16, in <module>
    from mmdet.datasets.api_wrappers import COCO, COCOeval, COCOevalMP
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/datasets/__init__.py", line 31, in <module>
    from .utils import get_loading_pipeline
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/datasets/utils.py", line 5, in <module>
    from mmdet.datasets.transforms import LoadAnnotations, LoadPanopticAnnotations
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/datasets/transforms/__init__.py", line 6, in <module>
    from .formatting import (ImageToTensor, PackDetInputs, PackReIDInputs,
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/datasets/transforms/formatting.py", line 11, in <module>
    from mmdet.structures.bbox import BaseBoxes
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/structures/bbox/__init__.py", line 2, in <module>
    from .base_boxes import BaseBoxes
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/structures/bbox/base_boxes.py", line 9, in <module>
    from mmdet.structures.mask.structures import BitmapMasks, PolygonMasks
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/structures/mask/__init__.py", line 3, in <module>
    from .structures import (BaseInstanceMasks, BitmapMasks, PolygonMasks,
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmdet/structures/mask/structures.py", line 12, in <module>
    from mmcv.ops.roi_align import roi_align
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmcv/ops/__init__.py", line 3, in <module>
    from .active_rotated_filter import active_rotated_filter
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmcv/ops/active_rotated_filter.py", line 10, in <module>
    ext_module = ext_loader.load_ext(
                 ^^^^^^^^^^^^^^^^^^^^
  File "/home/user/Projects/rtmdet/.venv/lib/python3.11/site-packages/mmcv/utils/ext_loader.py", line 13, in load_ext
    ext = importlib.import_module('mmcv.' + name)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.pyenv/versions/3.11.4/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'mmcv._ext'

In short, install mmcv-full...

That _ext seems to be related to CUDA opcodes? <- Needs checking.

KeyError: 'PlateCocoDataset is not in the mmdet::dataset registry

KeyError: 'PlateCocoDataset is not in the mmdet::dataset registry. Please check whether the value of `PlateCocoDataset` is correct or it was registered as expected. More details can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#import-the-custom-module'

See #Import the custom module.

If it still happens after adding it, check whether the file has been imported.

See also

Favorite site

author Zer0 sitemap