ZhengChong commited on
Commit ·
6a6227f
1
Parent(s): 82131f3
chore: Add SCHP model and detectron2 dependencies
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- app.pyAdded+373
- model/DensePose/__init__.pyAdded+158
- model/DensePose/__pycache__/__init__.cpython-310.pycAdded
- model/DensePose/__pycache__/__init__.cpython-312.pycAdded
- model/DensePose/__pycache__/__init__.cpython-39.pycAdded
- model/SCHP/LICENSEAdded+21
- model/SCHP/README.mdAdded+129
- model/SCHP/__init__.pyAdded+163
- model/SCHP/__pycache__/__init__.cpython-310.pycAdded
- model/SCHP/__pycache__/__init__.cpython-39.pycAdded
- model/SCHP/datasets/__init__.pyAdded
- model/SCHP/datasets/__pycache__/__init__.cpython-39.pycAdded
- model/SCHP/datasets/__pycache__/simple_extractor_dataset.cpython-39.pycAdded
- model/SCHP/datasets/datasets.pyAdded+205
- model/SCHP/datasets/simple_extractor_dataset.pyAdded+92
- model/SCHP/datasets/target_generation.pyAdded+40
- model/SCHP/environment.yamlAdded+49
- model/SCHP/evaluate.pyAdded+210
- model/SCHP/file_list.txtAdded
- model/SCHP/mhp_extension/.ipynb_checkpoints/demo-checkpoint.ipynbAdded
- model/SCHP/mhp_extension/README.mdAdded+38
- model/SCHP/mhp_extension/coco_style_annotation_creator/__pycache__/pycococreatortools.cpython-37.pycAdded
- model/SCHP/mhp_extension/coco_style_annotation_creator/human_to_coco.pyAdded+166
- model/SCHP/mhp_extension/coco_style_annotation_creator/pycococreatortools.pyAdded+114
- model/SCHP/mhp_extension/coco_style_annotation_creator/test_human2coco_format.pyAdded+74
- model/SCHP/mhp_extension/data/DemoDataset/global_pic/demo.jpgAdded
- model/SCHP/mhp_extension/demo.ipynbAdded
- model/SCHP/mhp_extension/demo/demo.jpgAdded
- model/SCHP/mhp_extension/demo/demo_global_human_parsing.pngAdded
- model/SCHP/mhp_extension/demo/demo_instance_human_mask.pngAdded
- model/SCHP/mhp_extension/demo/demo_multiple_human_parsing.pngAdded
- model/SCHP/mhp_extension/detectron2/.circleci/config.ymlAdded+179
- model/SCHP/mhp_extension/detectron2/.clang-formatAdded+85
- model/SCHP/mhp_extension/detectron2/.flake8Added+9
- model/SCHP/mhp_extension/detectron2/.github/CODE_OF_CONDUCT.mdAdded+5
- model/SCHP/mhp_extension/detectron2/.github/CONTRIBUTING.mdAdded+49
- model/SCHP/mhp_extension/detectron2/.github/Detectron2-Logo-Horz.svgAdded
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE.mdAdded+5
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/bugs.mdAdded+36
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/config.ymlAdded+9
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/feature-request.mdAdded+31
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/questions-help-support.mdAdded+26
- model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/unexpected-problems-bugs.mdAdded+45
- model/SCHP/mhp_extension/detectron2/.github/pull_request_template.mdAdded+9
- model/SCHP/mhp_extension/detectron2/.gitignoreAdded+46
- model/SCHP/mhp_extension/detectron2/GETTING_STARTED.mdAdded+79
- model/SCHP/mhp_extension/detectron2/INSTALL.mdAdded+184
- model/SCHP/mhp_extension/detectron2/LICENSEAdded+201
- model/SCHP/mhp_extension/detectron2/MODEL_ZOO.mdAdded+903
- model/SCHP/mhp_extension/detectron2/README.mdAdded+56
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373import argparseimport osfrom datetime import datetime
import gradio as grimport numpy as npimport torchfrom diffusers.image_processor import VaeImageProcessorfrom huggingface_hub import snapshot_downloadfrom PIL import Image
from model.cloth_masker import AutoMasker, vis_maskfrom model.pipeline import CatVTONPipelinefrom utils import init_weight_dtype, resize_and_crop, resize_and_padding
def parse_args(): parser = argparse.ArgumentParser(description="Simple example of a training script.") parser.add_argument( "--base_model_path", type=str, default="runwayml/stable-diffusion-inpainting", help=( "The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub." ), ) parser.add_argument( "--resume_path", type=str, default="zhengchong/CatVTON", help=( "The Path to the checkpoint of trained tryon model." ), ) parser.add_argument( "--output_dir", type=str, default="resource/demo/output", help="The output directory where the model predictions will be written.", )
parser.add_argument( "--width", type=int, default=768, help=( "The resolution for input images, all the images in the train/validation dataset will be resized to this" " resolution" ), ) parser.add_argument( "--height", type=int, default=1024, help=( "The resolution for input images, all the images in the train/validation dataset will be resized to this" " resolution" ), ) parser.add_argument( "--repaint", action="store_true", help="Whether to repaint the result image with the original background." ) parser.add_argument( "--allow_tf32", action="store_true", default=True, help=( "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see" " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices" ), ) parser.add_argument( "--mixed_precision", type=str, default="bf16", choices=["no", "fp16", "bf16"], help=( "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the" " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." ), ) # parser.add_argument( # "--enable_condition_noise", # action="store_true", # default=True, # help="Whether or not to enable condition noise.", # ) args = parser.parse_args() env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) if env_local_rank != -1 and env_local_rank != args.local_rank: args.local_rank = env_local_rank
return args
def image_grid(imgs, rows, cols): assert len(imgs) == rows * cols
w, h = imgs[0].size grid = Image.new("RGB", size=(cols * w, rows * h))
for i, img in enumerate(imgs): grid.paste(img, box=(i % cols * w, i // cols * h)) return grid
args = parse_args()repo_path = snapshot_download(repo_id=args.resume_path)# Pipelinepipeline = CatVTONPipeline( base_ckpt=args.base_model_path, attn_ckpt=repo_path, attn_ckpt_version="mix", weight_dtype=init_weight_dtype(args.mixed_precision), use_tf32=args.allow_tf32, device='cuda')# AutoMaskermask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)automasker = AutoMasker( densepose_ckpt=os.path.join(repo_path, "DensePose"), schp_ckpt=os.path.join(repo_path, "SCHP"), device='cuda', )
def submit_function( person_image, cloth_image, cloth_type, num_inference_steps, guidance_scale, seed, show_type): person_image, mask = person_image["background"], person_image["layers"][0] mask = Image.open(mask).convert("L") if len(np.unique(np.array(mask))) == 1: mask = None else: mask = np.array(mask) mask[mask > 0] = 255 mask = Image.fromarray(mask)
tmp_folder = args.output_dir date_str = datetime.now().strftime("%Y%m%d%H%M%S") result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png") if not os.path.exists(os.path.join(tmp_folder, date_str[:8])): os.makedirs(os.path.join(tmp_folder, date_str[:8]))
generator = None if seed != -1: generator = torch.Generator(device='cuda').manual_seed(seed)
person_image = Image.open(person_image).convert("RGB") cloth_image = Image.open(cloth_image).convert("RGB") person_image = resize_and_crop(person_image, (args.width, args.height)) cloth_image = resize_and_padding(cloth_image, (args.width, args.height)) # Process mask if mask is not None: mask = resize_and_crop(mask, (args.width, args.height)) else: mask = automasker( person_image, cloth_type )['mask'] mask = mask_processor.blur(mask, blur_factor=9)
# Inference # try: result_image = pipeline( image=person_image, condition_image=cloth_image, mask=mask, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator )[0] # except Exception as e: # raise gr.Error( # "An error occurred. Please try again later: {}".format(e) # ) # Post-process masked_person = vis_mask(person_image, mask) save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4) save_result_image.save(result_save_path) if show_type == "result only": return result_image else: width, height = person_image.size if show_type == "input & result": condition_width = width // 2 conditions = image_grid([person_image, cloth_image], 2, 1) else: condition_width = width // 3 conditions = image_grid([person_image, masked_person , cloth_image], 3, 1) conditions = conditions.resize((condition_width, height), Image.NEAREST) new_result_image = Image.new("RGB", (width + condition_width + 5, height)) new_result_image.paste(conditions, (0, 0)) new_result_image.paste(result_image, (condition_width + 5, 0)) return new_result_image
def person_example_fn(image_path): return image_path
HEADER = """<h1 style="text-align: center;"> 🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models </h1><div style="display: flex; justify-content: center; align-items: center;"> <a href="http://arxiv.org/abs/2407.15886" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/arXiv-2407.15886-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'> </a> <a href='https://huggingface.co/zhengchong/CatVTON' style="margin: 0 2px;"> <img src='https://img.shields.io/badge/Hugging Face-ckpts-orange?style=flat&logo=HuggingFace&logoColor=orange' alt='huggingface'> </a> <a href="https://github.com/Zheng-Chong/CatVTON" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'> </a> <a href="http://120.76.142.206:8888" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'> </a> <a href='https://zheng-chong.github.io/CatVTON/' style="margin: 0 2px;"> <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'> </a> <a href="https://github.com/Zheng-Chong/CatVTON/LICENCE" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'> </a></div>"""
def app_gradio(): with gr.Blocks(title="CatVTON") as demo: gr.Markdown(HEADER) with gr.Row(): with gr.Column(scale=1, min_width=350): with gr.Row(): image_path = gr.Image( type="filepath", interactive=True, visible=False, ) person_image = gr.ImageEditor( interactive=True, label="Person Image", type="filepath" )
with gr.Row(): with gr.Column(scale=1, min_width=230): cloth_image = gr.Image( interactive=True, label="Condition Image", type="filepath" ) with gr.Column(scale=1, min_width=120): gr.Markdown( '<span style="color: #808080; font-size: small;">Two ways to provide Mask:<br>1. Upload the person image and use the `🖌️` above to draw the Mask (higher priority)<br>2. Select the `Try-On Cloth Type` to generate automatically </span>' ) cloth_type = gr.Radio( label="Try-On Cloth Type", choices=["upper", "lower", "overall"], value="upper", )
submit = gr.Button("Submit") gr.Markdown( '<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>' ) gr.Markdown( '<span style="color: #808080; font-size: small;">Advanced options can adjust details:<br>1. `Inference Step` may enhance details;<br>2. `CFG` is highly correlated with saturation;<br>3. `Random seed` may improve pseudo-shadow.</span>' ) with gr.Accordion("Advanced Options", open=False): num_inference_steps = gr.Slider( label="Inference Step", minimum=10, maximum=100, step=5, value=50 ) # Guidence Scale guidance_scale = gr.Slider( label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5 ) # Random Seed seed = gr.Slider( label="Seed", minimum=-1, maximum=10000, step=1, value=42 ) show_type = gr.Radio( label="Show Type", choices=["result only", "input & result", "input & mask & result"], value="input & mask & result", )
with gr.Column(scale=2, min_width=500): result_image = gr.Image(interactive=False, label="Result") with gr.Row(): # Photo Examples root_path = "resource/demo/example" with gr.Column(): men_exm = gr.Examples( examples=[ os.path.join(root_path, "person", "men", _) for _ in os.listdir(os.path.join(root_path, "person", "men")) ], examples_per_page=4, inputs=image_path, label="Person Examples ①", ) women_exm = gr.Examples( examples=[ os.path.join(root_path, "person", "women", _) for _ in os.listdir(os.path.join(root_path, "person", "women")) ], examples_per_page=4, inputs=image_path, label="Person Examples ②", ) gr.Markdown( '<span style="color: #808080; font-size: small;">*Person examples come from the demos of <a href="https://huggingface.co/spaces/levihsu/OOTDiffusion">OOTDiffusion</a> and <a href="https://www.outfitanyone.org">OutfitAnyone</a>. </span>' ) with gr.Column(): condition_upper_exm = gr.Examples( examples=[ os.path.join(root_path, "condition", "upper", _) for _ in os.listdir(os.path.join(root_path, "condition", "upper")) ], examples_per_page=4, inputs=cloth_image, label="Condition Upper Examples", ) condition_overall_exm = gr.Examples( examples=[ os.path.join(root_path, "condition", "overall", _) for _ in os.listdir(os.path.join(root_path, "condition", "overall")) ], examples_per_page=4, inputs=cloth_image, label="Condition Overall Examples", ) condition_person_exm = gr.Examples( examples=[ os.path.join(root_path, "condition", "person", _) for _ in os.listdir(os.path.join(root_path, "condition", "person")) ], examples_per_page=4, inputs=cloth_image, label="Condition Reference Person Examples", ) gr.Markdown( '<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>' )
image_path.change( person_example_fn, inputs=image_path, outputs=person_image )
submit.click( submit_function, [ person_image, cloth_image, cloth_type, num_inference_steps, guidance_scale, seed, show_type, ], result_image, ) demo.queue().launch(share=True, show_error=True)
if __name__ == "__main__": app_gradio()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
import globimport osfrom random import randintimport shutilimport time
import cv2import numpy as npimport torchfrom PIL import Imagefrom densepose import add_densepose_configfrom densepose.vis.base import CompoundVisualizerfrom densepose.vis.densepose_results import DensePoseResultsFineSegmentationVisualizerfrom densepose.vis.extractor import create_extractor, CompoundExtractorfrom detectron2.config import get_cfgfrom detectron2.data.detection_utils import read_imagefrom detectron2.engine.defaults import DefaultPredictor
class DensePose: """ DensePose used in this project is from Detectron2 (https://github.com/facebookresearch/detectron2). These codes are modified from https://github.com/facebookresearch/detectron2/tree/main/projects/DensePose. The checkpoint is downloaded from https://github.com/facebookresearch/detectron2/blob/main/projects/DensePose/doc/DENSEPOSE_IUV.md#ModelZoo.
We use the model R_50_FPN_s1x with id 165712039, but other models should also work. The config file is downloaded from https://github.com/facebookresearch/detectron2/tree/main/projects/DensePose/configs. Noted that the config file should match the model checkpoint and Base-DensePose-RCNN-FPN.yaml is also needed. """
def __init__(self, model_path="./checkpoints/densepose_", device="cuda"): self.device = device self.config_path = os.path.join(model_path, 'densepose_rcnn_R_50_FPN_s1x.yaml') self.model_path = os.path.join(model_path, 'model_final_162be9.pkl') self.visualizations = ["dp_segm"] self.VISUALIZERS = {"dp_segm": DensePoseResultsFineSegmentationVisualizer} self.min_score = 0.8
self.cfg = self.setup_config() self.predictor = DefaultPredictor(self.cfg) self.predictor.model.to(self.device)
def setup_config(self): opts = ["MODEL.ROI_HEADS.SCORE_THRESH_TEST", str(self.min_score)] cfg = get_cfg() add_densepose_config(cfg) cfg.merge_from_file(self.config_path) cfg.merge_from_list(opts) cfg.MODEL.WEIGHTS = self.model_path cfg.freeze() return cfg
@staticmethod def _get_input_file_list(input_spec: str): if os.path.isdir(input_spec): file_list = [os.path.join(input_spec, fname) for fname in os.listdir(input_spec) if os.path.isfile(os.path.join(input_spec, fname))] elif os.path.isfile(input_spec): file_list = [input_spec] else: file_list = glob.glob(input_spec) return file_list
def create_context(self, cfg, output_path): vis_specs = self.visualizations visualizers = [] extractors = [] for vis_spec in vis_specs: texture_atlas = texture_atlases_dict = None vis = self.VISUALIZERS[vis_spec]( cfg=cfg, texture_atlas=texture_atlas, texture_atlases_dict=texture_atlases_dict, alpha=1.0 ) visualizers.append(vis) extractor = create_extractor(vis) extractors.append(extractor) visualizer = CompoundVisualizer(visualizers) extractor = CompoundExtractor(extractors) context = { "extractor": extractor, "visualizer": visualizer, "out_fname": output_path, "entry_idx": 0, } return context
def execute_on_outputs(self, context, entry, outputs): extractor = context["extractor"]
data = extractor(outputs)
H, W, _ = entry["image"].shape result = np.zeros((H, W), dtype=np.uint8)
data, box = data[0] x, y, w, h = [int(_) for _ in box[0].cpu().numpy()] i_array = data[0].labels[None].cpu().numpy()[0] result[y:y + h, x:x + w] = i_array result = Image.fromarray(result) result.save(context["out_fname"])
def __call__(self, image_or_path, resize=512) -> Image.Image: """ :param image_or_path: Path of the input image. :param resize: Resize the input image if its max size is larger than this value. :return: Dense pose image. """ # random tmp path with timestamp tmp_path = f"./densepose_/tmp/" if not os.path.exists(tmp_path): os.makedirs(tmp_path)
image_path = os.path.join(tmp_path, f"{int(time.time())}-{self.device}-{randint(0, 100000)}.png") if isinstance(image_or_path, str): assert image_or_path.split(".")[-1] in ["jpg", "png"], "Only support jpg and png images." shutil.copy(image_or_path, image_path) elif isinstance(image_or_path, Image.Image): image_or_path.save(image_path) else: shutil.rmtree(tmp_path) raise TypeError("image_path must be str or PIL.Image.Image")
output_path = image_path.replace(".png", "_dense.png").replace(".jpg", "_dense.png") w, h = Image.open(image_path).size
file_list = self._get_input_file_list(image_path) assert len(file_list), "No input images found!" context = self.create_context(self.cfg, output_path) for file_name in file_list: img = read_image(file_name, format="BGR") # predictor expects BGR image. # resize if (_ := max(img.shape)) > resize: scale = resize / _ img = cv2.resize(img, (int(img.shape[1] * scale), int(img.shape[0] * scale)))
with torch.no_grad(): outputs = self.predictor(img)["instances"] try: self.execute_on_outputs(context, {"file_name": file_name, "image": img}, outputs) except Exception as e: null_gray = Image.new('L', (1, 1)) null_gray.save(output_path)
dense_gray = Image.open(output_path).convert("L") dense_gray = dense_gray.resize((w, h), Image.NEAREST) # remove image_path and output_path os.remove(image_path) os.remove(output_path)
return dense_gray
if __name__ == '__main__': pass123456789101112131415161718192021MIT License
Copyright (c) 2020 Peike Li
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# Self Correction for Human Parsing
[](https://opensource.org/licenses/MIT)
An out-of-box human parsing representation extractor.
Our solution ranks 1st for all human parsing tracks (including single, multiple and video) in the third LIP challenge!

Features:- [x] Out-of-box human parsing extractor for other downstream applications.- [x] Pretrained model on three popular single person human parsing datasets.- [x] Training and inferecne code.- [x] Simple yet effective extension on multi-person and video human parsing tasks.
## Requirements
```conda env create -f environment.yamlconda activate schppip install -r requirements.txt```
## Simple Out-of-Box Extractor
The easiest way to get started is to use our trained SCHP models on your own images to extract human parsing representations. Here we provided state-of-the-art [trained models](https://drive.google.com/drive/folders/1uOaQCpNtosIjEL2phQKEdiYd0Td18jNo?usp=sharing) on three popular datasets. Theses three datasets have different label system, you can choose the best one to fit on your own task.
**LIP** ([exp-schp-201908261155-lip.pth](https://drive.google.com/file/d/1k4dllHpu0bdx38J7H28rVVLpU-kOHmnH/view?usp=sharing))
* mIoU on LIP validation: **59.36 %**.
* LIP is the largest single person human parsing dataset with 50000+ images. This dataset focus more on the complicated real scenarios. LIP has 20 labels, including 'Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'Upper-clothes', 'Dress', 'Coat', 'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe', 'Right-shoe'.
**ATR** ([exp-schp-201908301523-atr.pth](https://drive.google.com/file/d/1ruJg4lqR_jgQPj-9K0PP-L2vJERYOxLP/view?usp=sharing))
* mIoU on ATR test: **82.29%**.
* ATR is a large single person human parsing dataset with 17000+ images. This dataset focus more on fashion AI. ATR has 18 labels, including 'Background', 'Hat', 'Hair', 'Sunglasses', 'Upper-clothes', 'Skirt', 'Pants', 'Dress', 'Belt', 'Left-shoe', 'Right-shoe', 'Face', 'Left-leg', 'Right-leg', 'Left-arm', 'Right-arm', 'Bag', 'Scarf'.
**Pascal-Person-Part** ([exp-schp-201908270938-pascal-person-part.pth](https://drive.google.com/file/d/1E5YwNKW2VOEayK9mWCS3Kpsxf-3z04ZE/view?usp=sharing))
* mIoU on Pascal-Person-Part validation: **71.46** %.
* Pascal Person Part is a tiny single person human parsing dataset with 3000+ images. This dataset focus more on body parts segmentation. Pascal Person Part has 7 labels, including 'Background', 'Head', 'Torso', 'Upper Arms', 'Lower Arms', 'Upper Legs', 'Lower Legs'.
Choose one and have fun on your own task!
To extract the human parsing representation, simply put your own image in the `INPUT_PATH` folder, then download a pretrained model and run the following command. The output images with the same file name will be saved in `OUTPUT_PATH`
```python simple_extractor.py --dataset [DATASET] --model-restore [CHECKPOINT_PATH] --input-dir [INPUT_PATH] --output-dir [OUTPUT_PATH]```
**[Updated]** Here is also a [colab demo example](https://colab.research.google.com/drive/1JOwOPaChoc9GzyBi5FUEYTSaP2qxJl10?usp=sharing) for quick inference provided by [@levindabhi](https://github.com/levindabhi).
The `DATASET` command has three options, including 'lip', 'atr' and 'pascal'. Note each pixel in the output images denotes the predicted label number. The output images have the same size as the input ones. To better visualization, we put a palette with the output images. We suggest you to read the image with `PIL`.
If you need not only the final parsing images, but also the feature map representations. Add `--logits` command to save the output feature maps. These feature maps are the logits before softmax layer.
## Dataset Preparation
Please download the [LIP](http://sysu-hcp.net/lip/) dataset following the below structure.
```commandlinedata/LIP|--- train_imgaes # 30462 training single person images|--- val_images # 10000 validation single person images|--- train_segmentations # 30462 training annotations|--- val_segmentations # 10000 training annotations|--- train_id.txt # training image list|--- val_id.txt # validation image list```
## Training
```python train.py ```By default, the trained model will be saved in `./log` directory. Please read the arguments for more details.
## Evaluation```python evaluate.py --model-restore [CHECKPOINT_PATH]```CHECKPOINT_PATH should be the path of trained model.
## Extension on Multiple Human Parsing
Please read [MultipleHumanParsing.md](./mhp_extension/README.md) for more details.
## Citation
Please cite our work if you find this repo useful in your research.
```latex@article{li2020self, title={Self-Correction for Human Parsing}, author={Li, Peike and Xu, Yunqiu and Wei, Yunchao and Yang, Yi}, journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, year={2020}, doi={10.1109/TPAMI.2020.3048039}}```
## Visualization
* Source Image.* LIP Parsing Result.* ATR Parsing Result.* Pascal-Person-Part Parsing Result.* Source Image.* Instance Human Mask.* Global Human Parsing Result.* Multiple Human Parsing Result.
## RelatedOur code adopts the [InplaceSyncBN](https://github.com/mapillary/inplace_abn) to save gpu memory cost.
There is also a [PaddlePaddle](https://github.com/PaddlePaddle/PaddleSeg/tree/develop/contrib/ACE2P) Implementation of this project.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163from model.SCHP import networksfrom model.SCHP.utils.transforms import get_affine_transform, transform_logits
from collections import OrderedDictimport torchimport numpy as npimport cv2from PIL import Imagefrom torchvision import transforms
def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palette[j * 3 + 1] = 0 palette[j * 3 + 2] = 0 i = 0 while lab: palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i)) palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i)) palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i)) i += 1 lab >>= 3 return palette
dataset_settings = { 'lip': { 'input_size': [473, 473], 'num_classes': 20, 'label': ['Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'Upper-clothes', 'Dress', 'Coat', 'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe', 'Right-shoe'] }, 'atr': { 'input_size': [512, 512], 'num_classes': 18, 'label': ['Background', 'Hat', 'Hair', 'Sunglasses', 'Upper-clothes', 'Skirt', 'Pants', 'Dress', 'Belt', 'Left-shoe', 'Right-shoe', 'Face', 'Left-leg', 'Right-leg', 'Left-arm', 'Right-arm', 'Bag', 'Scarf'] }, 'pascal': { 'input_size': [512, 512], 'num_classes': 7, 'label': ['Background', 'Head', 'Torso', 'Upper Arms', 'Lower Arms', 'Upper Legs', 'Lower Legs'], }}
class SCHP: def __init__(self, ckpt_path, device): dataset_type = None if 'lip' in ckpt_path: dataset_type = 'lip' elif 'atr' in ckpt_path: dataset_type = 'atr' elif 'pascal' in ckpt_path: dataset_type = 'pascal' assert dataset_type is not None, 'Dataset type not found in checkpoint path' self.device = device self.num_classes = dataset_settings[dataset_type]['num_classes'] self.input_size = dataset_settings[dataset_type]['input_size'] self.aspect_ratio = self.input_size[1] * 1.0 / self.input_size[0] self.palette = get_palette(self.num_classes)
self.label = dataset_settings[dataset_type]['label'] self.model = networks.init_model('resnet101', num_classes=self.num_classes, pretrained=None).to(device) self.load_ckpt(ckpt_path) self.model.eval() self.transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.406, 0.456, 0.485], std=[0.225, 0.224, 0.229]) ]) self.upsample = torch.nn.Upsample(size=self.input_size, mode='bilinear', align_corners=True)
def load_ckpt(self, ckpt_path): state_dict = torch.load(ckpt_path, map_location='cpu')['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k[7:] # remove `module.` new_state_dict[name] = v self.model.load_state_dict(new_state_dict)
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w, h], dtype=np.float32) return center, scale
def preprocess(self, image): if isinstance(image, str): img = cv2.imread(image, cv2.IMREAD_COLOR) elif isinstance(image, Image.Image): # to cv2 format img = np.array(image) h, w, _ = img.shape # Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0 trans = get_affine_transform(person_center, s, r, self.input_size) input = cv2.warpAffine( img, trans, (int(self.input_size[1]), int(self.input_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
input = self.transform(input).to(self.device).unsqueeze(0) meta = { 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r } return input, meta
def __call__(self, image_or_path): if isinstance(image_or_path, list): image_list = [] meta_list = [] for image in image_or_path: image, meta = self.preprocess(image) image_list.append(image) meta_list.append(meta) image = torch.cat(image_list, dim=0) else: image, meta = self.preprocess(image_or_path) meta_list = [meta] output = self.model(image) upsample_outputs = self.upsample(output[0][-1]) upsample_outputs = upsample_outputs.permute(0, 2, 3, 1) # BCHW -> BHWC
output_img_list = [] for upsample_output, meta in zip(upsample_outputs, meta_list): c, s, w, h = meta['center'], meta['scale'], meta['width'], meta['height'] logits_result = transform_logits(upsample_output.data.cpu().numpy(), c, s, w, h, input_size=self.input_size) parsing_result = np.argmax(logits_result, axis=2) output_img = Image.fromarray(np.asarray(parsing_result, dtype=np.uint8)) output_img.putpalette(self.palette) output_img_list.append(output_img)
return output_img_list[0] if len(output_img_list) == 1 else output_img_list123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205#!/usr/bin/env python# -*- encoding: utf-8 -*-
"""@Author : Peike Li@Contact : peike.li@yahoo.com@File : datasets.py@Time : 8/4/19 3:35 PM@Desc :@License : This source code is licensed under the license found in the LICENSE file in the root directory of this source tree."""
import osimport numpy as npimport randomimport torchimport cv2from torch.utils import datafrom utils.transforms import get_affine_transform
class LIPDataSet(data.Dataset): def __init__(self, root, dataset, crop_size=[473, 473], scale_factor=0.25, rotation_factor=30, ignore_label=255, transform=None): self.root = root self.aspect_ratio = crop_size[1] * 1.0 / crop_size[0] self.crop_size = np.asarray(crop_size) self.ignore_label = ignore_label self.scale_factor = scale_factor self.rotation_factor = rotation_factor self.flip_prob = 0.5 self.transform = transform self.dataset = dataset
list_path = os.path.join(self.root, self.dataset + '_id.txt') train_list = [i_id.strip() for i_id in open(list_path)]
self.train_list = train_list self.number_samples = len(self.train_list)
def __len__(self): return self.number_samples
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w * 1.0, h * 1.0], dtype=np.float32) return center, scale
def __getitem__(self, index): train_item = self.train_list[index]
im_path = os.path.join(self.root, self.dataset + '_images', train_item + '.jpg') parsing_anno_path = os.path.join(self.root, self.dataset + '_segmentations', train_item + '.png')
im = cv2.imread(im_path, cv2.IMREAD_COLOR) h, w, _ = im.shape parsing_anno = np.zeros((h, w), dtype=np.long)
# Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0
if self.dataset != 'test': # Get pose annotation parsing_anno = cv2.imread(parsing_anno_path, cv2.IMREAD_GRAYSCALE) if self.dataset == 'train' or self.dataset == 'trainval': sf = self.scale_factor rf = self.rotation_factor s = s * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf) r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) if random.random() <= 0.6 else 0
if random.random() <= self.flip_prob: im = im[:, ::-1, :] parsing_anno = parsing_anno[:, ::-1] person_center[0] = im.shape[1] - person_center[0] - 1 right_idx = [15, 17, 19] left_idx = [14, 16, 18] for i in range(0, 3): right_pos = np.where(parsing_anno == right_idx[i]) left_pos = np.where(parsing_anno == left_idx[i]) parsing_anno[right_pos[0], right_pos[1]] = left_idx[i] parsing_anno[left_pos[0], left_pos[1]] = right_idx[i]
trans = get_affine_transform(person_center, s, r, self.crop_size) input = cv2.warpAffine( im, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
if self.transform: input = self.transform(input)
meta = { 'name': train_item, 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r }
if self.dataset == 'val' or self.dataset == 'test': return input, meta else: label_parsing = cv2.warpAffine( parsing_anno, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=(255))
label_parsing = torch.from_numpy(label_parsing)
return input, label_parsing, meta
class LIPDataValSet(data.Dataset): def __init__(self, root, dataset='val', crop_size=[473, 473], transform=None, flip=False): self.root = root self.crop_size = crop_size self.transform = transform self.flip = flip self.dataset = dataset self.root = root self.aspect_ratio = crop_size[1] * 1.0 / crop_size[0] self.crop_size = np.asarray(crop_size)
val_list=[] for root, dirs, files in os.walk("/home/chongzheng_p23/data/Datasets/UniFashion/YOOX/YOOX-Images"): for file in files: if file.endswith(".jpg"): source_file_path = os.path.join(root, file) val_list.append(source_file_path)
self.val_list = val_list self.number_samples = len(self.val_list)
def __len__(self): return len(self.val_list)
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w * 1.0, h * 1.0], dtype=np.float32)
return center, scale
def __getitem__(self, index): val_item = self.val_list[index] # Load training image im_path = val_item im = cv2.imread(im_path, cv2.IMREAD_COLOR) h, w, _ = im.shape # Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0 trans = get_affine_transform(person_center, s, r, self.crop_size) input = cv2.warpAffine( im, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0)) input = self.transform(input) flip_input = input.flip(dims=[-1]) if self.flip: batch_input_im = torch.stack([input, flip_input]) else: batch_input_im = input
meta = { 'name': val_item, #root 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r }
return batch_input_im, meta1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python# -*- encoding: utf-8 -*-
"""@Author : Peike Li@Contact : peike.li@yahoo.com@File : dataset.py@Time : 8/30/19 9:12 PM@Desc : Dataset Definition@License : This source code is licensed under the license found in the LICENSE file in the root directory of this source tree."""
import osimport cv2import numpy as np
from torch.utils import datafrom utils.transforms import get_affine_transform
class SimpleFolderDataset(data.Dataset): def __init__(self, root, input_size=[512, 512], transform=None): self.root = root self.input_size = input_size self.transform = transform self.aspect_ratio = input_size[1] * 1.0 / input_size[0] self.input_size = np.asarray(input_size)
self.file_list=[] self.root_list=[] for root, dirs, files in os.walk(root): for file in files: if file.endswith(".jpg"): source_file_path = os.path.join(root, file) self.file_list.append(source_file_path) self.root_list.append(root)
def __len__(self): return len(self.file_list)
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w, h], dtype=np.float32) return center, scale
def __getitem__(self, index): img_path = self.file_list[index] root = self.root_list[index] img_name = img_path.split("/")[-1].split(".")[0] img = cv2.imread(img_path, cv2.IMREAD_COLOR) if img is None: return self.__getitem__(index+1) else: h, w, _ = img.shape
# Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0 trans = get_affine_transform(person_center, s, r, self.input_size) input = cv2.warpAffine( img, trans, (int(self.input_size[1]), int(self.input_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
input = self.transform(input) meta = { 'img_path': img_path, 'name': img_name, 'root': root, 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r }
return input, meta12345678910111213141516171819202122232425262728293031323334353637383940import torchfrom torch.nn import functional as F
def generate_edge_tensor(label, edge_width=3): # label = label.type(torch.cuda.FloatTensor) if len(label.shape) == 2: label = label.unsqueeze(0) n, h, w = label.shape edge = torch.zeros(label.shape, dtype=torch.float)#.cuda() # right edge_right = edge[:, 1:h, :] edge_right[(label[:, 1:h, :] != label[:, :h - 1, :]) & (label[:, 1:h, :] != 255) & (label[:, :h - 1, :] != 255)] = 1
# up edge_up = edge[:, :, :w - 1] edge_up[(label[:, :, :w - 1] != label[:, :, 1:w]) & (label[:, :, :w - 1] != 255) & (label[:, :, 1:w] != 255)] = 1
# upright edge_upright = edge[:, :h - 1, :w - 1] edge_upright[(label[:, :h - 1, :w - 1] != label[:, 1:h, 1:w]) & (label[:, :h - 1, :w - 1] != 255) & (label[:, 1:h, 1:w] != 255)] = 1
# bottomright edge_bottomright = edge[:, :h - 1, 1:w] edge_bottomright[(label[:, :h - 1, 1:w] != label[:, 1:h, :w - 1]) & (label[:, :h - 1, 1:w] != 255) & (label[:, 1:h, :w - 1] != 255)] = 1
kernel = torch.ones((1, 1, edge_width, edge_width), dtype=torch.float)#.cuda() with torch.no_grad(): edge = edge.unsqueeze(1) edge = F.conv2d(edge, kernel, stride=1, padding=1) edge[edge!=0] = 1 edge = edge.squeeze() return edge12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849name: schpchannels: - pytorch - defaultsdependencies: - _libgcc_mutex=0.1=main - blas=1.0=mkl - ca-certificates=2020.12.8=h06a4308_0 - certifi=2020.12.5=py38h06a4308_0 - cudatoolkit=10.1.243=h6bb024c_0 - freetype=2.10.4=h5ab3b9f_0 - intel-openmp=2020.2=254 - jpeg=9b=h024ee3a_2 - lcms2=2.11=h396b838_0 - ld_impl_linux-64=2.33.1=h53a641e_7 - libedit=3.1.20191231=h14c3975_1 - libffi=3.3=he6710b0_2 - libgcc-ng=9.1.0=hdf63c60_0 - libpng=1.6.37=hbc83047_0 - libstdcxx-ng=9.1.0=hdf63c60_0 - libtiff=4.1.0=h2733197_1 - lz4-c=1.9.2=heb0550a_3 - mkl=2020.2=256 - mkl-service=2.3.0=py38he904b0f_0 - mkl_fft=1.2.0=py38h23d657b_0 - mkl_random=1.1.1=py38h0573a6f_0 - ncurses=6.2=he6710b0_1 - ninja=1.10.2=py38hff7bd54_0 - numpy=1.19.2=py38h54aff64_0 - numpy-base=1.19.2=py38hfa32c7d_0 - olefile=0.46=py_0 - openssl=1.1.1i=h27cfd23_0 - pillow=8.0.1=py38he98fc37_0 - pip=20.3.3=py38h06a4308_0 - python=3.8.5=h7579374_1 - readline=8.0=h7b6447c_0 - setuptools=51.0.0=py38h06a4308_2 - six=1.15.0=py38h06a4308_0 - sqlite=3.33.0=h62c20be_0 - tk=8.6.10=hbc83047_0 - tqdm=4.55.0=pyhd3eb1b0_0 - wheel=0.36.2=pyhd3eb1b0_0 - xz=5.2.5=h7b6447c_0 - zlib=1.2.11=h7b6447c_3 - zstd=1.4.5=h9ceee32_0 - pytorch=1.5.1=py3.8_cuda10.1.243_cudnn7.6.3_0 - torchvision=0.6.1=py38_cu101prefix: /home/peike/opt/anaconda3/envs/schp
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210#!/usr/bin/env python# -*- encoding: utf-8 -*-
"""@Author : Peike Li@Contact : peike.li@yahoo.com@File : evaluate.py@Time : 8/4/19 3:36 PM@Desc :@License : This source code is licensed under the license found in the LICENSE file in the root directory of this source tree."""
import osimport argparseimport numpy as npimport torch
from torch.utils import datafrom tqdm import tqdmfrom PIL import Image as PILImageimport torchvision.transforms as transformsimport torch.backends.cudnn as cudnn
import networksfrom datasets.datasets import LIPDataValSetfrom utils.miou import compute_mean_ioUfrom utils.transforms import BGR2RGB_transformfrom utils.transforms import transform_parsing
def get_arguments(): """Parse all the arguments provided from the CLI.
Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Self Correction for Human Parsing")
# Network Structure parser.add_argument("--arch", type=str, default='resnet101') # Data Preference parser.add_argument("--data-dir", type=str, default='./data/LIP') parser.add_argument("--batch-size", type=int, default=1) parser.add_argument("--input-size", type=str, default='473,473') parser.add_argument("--num-classes", type=int, default=20) parser.add_argument("--ignore-label", type=int, default=255) parser.add_argument("--random-mirror", action="store_true") parser.add_argument("--random-scale", action="store_true") # Evaluation Preference parser.add_argument("--log-dir", type=str, default='./log') parser.add_argument("--model-restore", type=str, default='/data1/chongzheng/zhangwq/Self-Correction-Human-Parsing-master/exp-schp-201908301523-atr.pth') parser.add_argument("--gpu", type=str, default='0', help="choose gpu device.") parser.add_argument("--save-results", action="store_true", help="whether to save the results.") parser.add_argument("--flip", action="store_true", help="random flip during the test.") parser.add_argument("--multi-scales", type=str, default='1', help="multiple scales during the test") return parser.parse_args()
def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palette[j * 3 + 1] = 0 palette[j * 3 + 2] = 0 i = 0 while lab: palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i)) palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i)) palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i)) i += 1 lab >>= 3 return palette
def multi_scale_testing(model, batch_input_im, crop_size=[473, 473], flip=True, multi_scales=[1]): flipped_idx = (15, 14, 17, 16, 19, 18) if len(batch_input_im.shape) > 4: batch_input_im = batch_input_im.squeeze() if len(batch_input_im.shape) == 3: batch_input_im = batch_input_im.unsqueeze(0)
interp = torch.nn.Upsample(size=crop_size, mode='bilinear', align_corners=True) ms_outputs = [] for s in multi_scales: interp_im = torch.nn.Upsample(scale_factor=s, mode='bilinear', align_corners=True) scaled_im = interp_im(batch_input_im) parsing_output = model(scaled_im) parsing_output = parsing_output[0][-1] output = parsing_output[0] if flip: flipped_output = parsing_output[1] flipped_output[14:20, :, :] = flipped_output[flipped_idx, :, :] output += flipped_output.flip(dims=[-1]) output *= 0.5 output = interp(output.unsqueeze(0)) ms_outputs.append(output[0]) ms_fused_parsing_output = torch.stack(ms_outputs) ms_fused_parsing_output = ms_fused_parsing_output.mean(0) ms_fused_parsing_output = ms_fused_parsing_output.permute(1, 2, 0) # HWC parsing = torch.argmax(ms_fused_parsing_output, dim=2) parsing = parsing.data.cpu().numpy() ms_fused_parsing_output = ms_fused_parsing_output.data.cpu().numpy() return parsing, ms_fused_parsing_output
def main(): """Create the model and start the evaluation process.""" args = get_arguments() multi_scales = [float(i) for i in args.multi_scales.split(',')] gpus = [int(i) for i in args.gpu.split(',')] assert len(gpus) == 1 if not args.gpu == 'None': os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
cudnn.benchmark = True cudnn.enabled = True
h, w = map(int, args.input_size.split(',')) input_size = [h, w]
model = networks.init_model(args.arch, num_classes=args.num_classes, pretrained=None)
IMAGE_MEAN = model.mean IMAGE_STD = model.std INPUT_SPACE = model.input_space print('image mean: {}'.format(IMAGE_MEAN)) print('image std: {}'.format(IMAGE_STD)) print('input space:{}'.format(INPUT_SPACE)) if INPUT_SPACE == 'BGR': print('BGR Transformation') transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=IMAGE_MEAN, std=IMAGE_STD),
]) if INPUT_SPACE == 'RGB': print('RGB Transformation') transform = transforms.Compose([ transforms.ToTensor(), BGR2RGB_transform(), transforms.Normalize(mean=IMAGE_MEAN, std=IMAGE_STD), ])
# Data loader lip_test_dataset = LIPDataValSet(args.data_dir, 'val', crop_size=input_size, transform=transform, flip=args.flip) num_samples = len(lip_test_dataset) print('Totoal testing sample numbers: {}'.format(num_samples)) testloader = data.DataLoader(lip_test_dataset, batch_size=args.batch_size, shuffle=False, pin_memory=True)
# Load model weight state_dict = torch.load(args.model_restore)['state_dict'] from collections import OrderedDict new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k[7:] # remove `module.` new_state_dict[name] = v model.load_state_dict(new_state_dict) model.cuda() model.eval()
sp_results_dir = os.path.join(args.log_dir, 'sp_results') if not os.path.exists(sp_results_dir): os.makedirs(sp_results_dir)
palette = get_palette(20) parsing_preds = [] scales = np.zeros((num_samples, 2), dtype=np.float32) centers = np.zeros((num_samples, 2), dtype=np.int32) with torch.no_grad(): for idx, batch in enumerate(tqdm(testloader)): image, meta = batch if (len(image.shape) > 4): image = image.squeeze() im_name = meta['name'][0] c = meta['center'].numpy()[0] s = meta['scale'].numpy()[0] w = meta['width'].numpy()[0] h = meta['height'].numpy()[0] scales[idx, :] = s centers[idx, :] = c parsing, logits = multi_scale_testing(model, image.cuda(), crop_size=input_size, flip=args.flip, multi_scales=multi_scales) if args.save_results: parsing_result = transform_parsing(parsing, c, s, w, h, input_size) parsing_result_path = os.path.join(sp_results_dir, im_name + '.png') output_im = PILImage.fromarray(np.asarray(parsing_result, dtype=np.uint8)) output_im.putpalette(palette) output_im.save(parsing_result_path)
parsing_preds.append(parsing) assert len(parsing_preds) == num_samples mIoU = compute_mean_ioU(parsing_preds, scales, centers, args.num_classes, args.data_dir, input_size) print(mIoU) return
if __name__ == '__main__': main()1234567891011121314151617181920212223242526272829303132333435363738# Self Correction for Human Parsing
We propose a simple yet effective multiple human parsing framework by extending our self-correction network.
Here we show an example usage jupyter notebook in [demo.ipynb](./demo.ipynb).
## Requirements
Please see [INSTALL.md](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md) for further requirements.
## Citation
Please cite our work if you find this repo useful in your research.
```latex@article{li2019self, title={Self-Correction for Human Parsing}, author={Li, Peike and Xu, Yunqiu and Wei, Yunchao and Yang, Yi}, journal={arXiv preprint arXiv:1910.09777}, year={2019}}```
## Visualization
* Source Image.* Instance Human Mask.* Global Human Parsing Result.* Multiple Human Parsing Result.
## Related
Our implementation is based on the [Detectron2](https://github.com/facebookresearch/detectron2).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import argparseimport datetimeimport jsonimport osfrom PIL import Imageimport numpy as np
import pycococreatortools
def get_arguments(): parser = argparse.ArgumentParser(description="transform mask annotation to coco annotation") parser.add_argument("--dataset", type=str, default='CIHP', help="name of dataset (CIHP, MHPv2 or VIP)") parser.add_argument("--json_save_dir", type=str, default='../data/msrcnn_finetune_annotations', help="path to save coco-style annotation json file") parser.add_argument("--use_val", type=bool, default=False, help="use train+val set for finetuning or not") parser.add_argument("--train_img_dir", type=str, default='../data/instance-level_human_parsing/Training/Images', help="train image path") parser.add_argument("--train_anno_dir", type=str, default='../data/instance-level_human_parsing/Training/Human_ids', help="train human mask path") parser.add_argument("--val_img_dir", type=str, default='../data/instance-level_human_parsing/Validation/Images', help="val image path") parser.add_argument("--val_anno_dir", type=str, default='../data/instance-level_human_parsing/Validation/Human_ids', help="val human mask path") return parser.parse_args()
def main(args): INFO = { "description": args.split_name + " Dataset", "url": "", "version": "", "year": 2019, "contributor": "xyq", "date_created": datetime.datetime.utcnow().isoformat(' ') }
LICENSES = [ { "id": 1, "name": "", "url": "" } ]
CATEGORIES = [ { 'id': 1, 'name': 'person', 'supercategory': 'person', }, ]
coco_output = { "info": INFO, "licenses": LICENSES, "categories": CATEGORIES, "images": [], "annotations": [] }
image_id = 1 segmentation_id = 1
for image_name in os.listdir(args.train_img_dir): image = Image.open(os.path.join(args.train_img_dir, image_name)) image_info = pycococreatortools.create_image_info( image_id, image_name, image.size ) coco_output["images"].append(image_info)
human_mask_name = os.path.splitext(image_name)[0] + '.png' human_mask = np.asarray(Image.open(os.path.join(args.train_anno_dir, human_mask_name))) human_gt_labels = np.unique(human_mask)
for i in range(1, len(human_gt_labels)): category_info = {'id': 1, 'is_crowd': 0} binary_mask = np.uint8(human_mask == i) annotation_info = pycococreatortools.create_annotation_info( segmentation_id, image_id, category_info, binary_mask, image.size, tolerance=10 ) if annotation_info is not None: coco_output["annotations"].append(annotation_info)
segmentation_id += 1 image_id += 1
if not os.path.exists(args.json_save_dir): os.makedirs(args.json_save_dir) if not args.use_val: with open('{}/{}_train.json'.format(args.json_save_dir, args.split_name), 'w') as output_json_file: json.dump(coco_output, output_json_file) else: for image_name in os.listdir(args.val_img_dir): image = Image.open(os.path.join(args.val_img_dir, image_name)) image_info = pycococreatortools.create_image_info( image_id, image_name, image.size ) coco_output["images"].append(image_info)
human_mask_name = os.path.splitext(image_name)[0] + '.png' human_mask = np.asarray(Image.open(os.path.join(args.val_anno_dir, human_mask_name))) human_gt_labels = np.unique(human_mask)
for i in range(1, len(human_gt_labels)): category_info = {'id': 1, 'is_crowd': 0} binary_mask = np.uint8(human_mask == i) annotation_info = pycococreatortools.create_annotation_info( segmentation_id, image_id, category_info, binary_mask, image.size, tolerance=10 ) if annotation_info is not None: coco_output["annotations"].append(annotation_info)
segmentation_id += 1 image_id += 1
with open('{}/{}_trainval.json'.format(args.json_save_dir, args.split_name), 'w') as output_json_file: json.dump(coco_output, output_json_file)
coco_output_val = { "info": INFO, "licenses": LICENSES, "categories": CATEGORIES, "images": [], "annotations": [] }
image_id_val = 1 segmentation_id_val = 1
for image_name in os.listdir(args.val_img_dir): image = Image.open(os.path.join(args.val_img_dir, image_name)) image_info = pycococreatortools.create_image_info( image_id_val, image_name, image.size ) coco_output_val["images"].append(image_info)
human_mask_name = os.path.splitext(image_name)[0] + '.png' human_mask = np.asarray(Image.open(os.path.join(args.val_anno_dir, human_mask_name))) human_gt_labels = np.unique(human_mask)
for i in range(1, len(human_gt_labels)): category_info = {'id': 1, 'is_crowd': 0} binary_mask = np.uint8(human_mask == i) annotation_info = pycococreatortools.create_annotation_info( segmentation_id_val, image_id_val, category_info, binary_mask, image.size, tolerance=10 ) if annotation_info is not None: coco_output_val["annotations"].append(annotation_info)
segmentation_id_val += 1 image_id_val += 1
with open('{}/{}_val.json'.format(args.json_save_dir, args.split_name), 'w') as output_json_file_val: json.dump(coco_output_val, output_json_file_val)
if __name__ == "__main__": args = get_arguments() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import reimport datetimeimport numpy as npfrom itertools import groupbyfrom skimage import measurefrom PIL import Imagefrom pycocotools import mask
convert = lambda text: int(text) if text.isdigit() else text.lower()natrual_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
def resize_binary_mask(array, new_size): image = Image.fromarray(array.astype(np.uint8) * 255) image = image.resize(new_size) return np.asarray(image).astype(np.bool_)
def close_contour(contour): if not np.array_equal(contour[0], contour[-1]): contour = np.vstack((contour, contour[0])) return contour
def binary_mask_to_rle(binary_mask): rle = {'counts': [], 'size': list(binary_mask.shape)} counts = rle.get('counts') for i, (value, elements) in enumerate(groupby(binary_mask.ravel(order='F'))): if i == 0 and value == 1: counts.append(0) counts.append(len(list(elements)))
return rle
def binary_mask_to_polygon(binary_mask, tolerance=0): """Converts a binary mask to COCO polygon representation Args: binary_mask: a 2D binary numpy array where '1's represent the object tolerance: Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned. """ polygons = [] # pad mask to close contours of shapes which start and end at an edge padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0) contours = measure.find_contours(padded_binary_mask, 0.5) contours = np.subtract(contours, 1) for contour in contours: contour = close_contour(contour) contour = measure.approximate_polygon(contour, tolerance) if len(contour) < 3: continue contour = np.flip(contour, axis=1) segmentation = contour.ravel().tolist() # after padding and subtracting 1 we may get -0.5 points in our segmentation segmentation = [0 if i < 0 else i for i in segmentation] polygons.append(segmentation)
return polygons
def create_image_info(image_id, file_name, image_size, date_captured=datetime.datetime.utcnow().isoformat(' '), license_id=1, coco_url="", flickr_url=""): image_info = { "id": image_id, "file_name": file_name, "width": image_size[0], "height": image_size[1], "date_captured": date_captured, "license": license_id, "coco_url": coco_url, "flickr_url": flickr_url }
return image_info
def create_annotation_info(annotation_id, image_id, category_info, binary_mask, image_size=None, tolerance=2, bounding_box=None): if image_size is not None: binary_mask = resize_binary_mask(binary_mask, image_size)
binary_mask_encoded = mask.encode(np.asfortranarray(binary_mask.astype(np.uint8)))
area = mask.area(binary_mask_encoded) if area < 1: return None
if bounding_box is None: bounding_box = mask.toBbox(binary_mask_encoded)
if category_info["is_crowd"]: is_crowd = 1 segmentation = binary_mask_to_rle(binary_mask) else: is_crowd = 0 segmentation = binary_mask_to_polygon(binary_mask, tolerance) if not segmentation: return None
annotation_info = { "id": annotation_id, "image_id": image_id, "category_id": category_info["id"], "iscrowd": is_crowd, "area": area.tolist(), "bbox": bounding_box.tolist(), "segmentation": segmentation, "width": binary_mask.shape[1], "height": binary_mask.shape[0], }
return annotation_info1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import argparseimport datetimeimport jsonimport osfrom PIL import Image
import pycococreatortools
def get_arguments(): parser = argparse.ArgumentParser(description="transform mask annotation to coco annotation") parser.add_argument("--dataset", type=str, default='CIHP', help="name of dataset (CIHP, MHPv2 or VIP)") parser.add_argument("--json_save_dir", type=str, default='../data/CIHP/annotations', help="path to save coco-style annotation json file") parser.add_argument("--test_img_dir", type=str, default='../data/CIHP/Testing/Images', help="test image path") return parser.parse_args()
args = get_arguments()
INFO = { "description": args.dataset + "Dataset", "url": "", "version": "", "year": 2020, "contributor": "yunqiuxu", "date_created": datetime.datetime.utcnow().isoformat(' ')}
LICENSES = [ { "id": 1, "name": "", "url": "" }]
CATEGORIES = [ { 'id': 1, 'name': 'person', 'supercategory': 'person', },]
def main(args): coco_output = { "info": INFO, "licenses": LICENSES, "categories": CATEGORIES, "images": [], "annotations": [] }
image_id = 1
for image_name in os.listdir(args.test_img_dir): image = Image.open(os.path.join(args.test_img_dir, image_name)) image_info = pycococreatortools.create_image_info( image_id, image_name, image.size ) coco_output["images"].append(image_info) image_id += 1
if not os.path.exists(os.path.join(args.json_save_dir)): os.mkdir(os.path.join(args.json_save_dir))
with open('{}/{}.json'.format(args.json_save_dir, args.dataset), 'w') as output_json_file: json.dump(coco_output, output_json_file)
if __name__ == "__main__": main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179# Python CircleCI 2.0 configuration file## Check https://circleci.com/docs/2.0/language-python/ for more details#version: 2
# -------------------------------------------------------------------------------------# Environments to run the jobs in# -------------------------------------------------------------------------------------cpu: &cpu docker: - image: circleci/python:3.6.8-stretch resource_class: medium
gpu: &gpu machine: image: ubuntu-1604:201903-01 docker_layer_caching: true resource_class: gpu.small
# -------------------------------------------------------------------------------------# Re-usable commands# -------------------------------------------------------------------------------------install_python: &install_python - run: name: Install Python working_directory: ~/ command: | pyenv install 3.6.1 pyenv global 3.6.1
setup_venv: &setup_venv - run: name: Setup Virtual Env working_directory: ~/ command: | python -m venv ~/venv echo ". ~/venv/bin/activate" >> $BASH_ENV . ~/venv/bin/activate python --version which python which pip pip install --upgrade pip
install_dep: &install_dep - run: name: Install Dependencies command: | pip install --progress-bar off -U 'git+https://github.com/facebookresearch/fvcore' pip install --progress-bar off cython opencv-python pip install --progress-bar off 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI' pip install --progress-bar off torch torchvision
install_detectron2: &install_detectron2 - run: name: Install Detectron2 command: | gcc --version pip install -U --progress-bar off -e .[dev] python -m detectron2.utils.collect_env
install_nvidia_driver: &install_nvidia_driver - run: name: Install nvidia driver working_directory: ~/ command: | wget -q 'https://s3.amazonaws.com/ossci-linux/nvidia_driver/NVIDIA-Linux-x86_64-430.40.run' sudo /bin/bash ./NVIDIA-Linux-x86_64-430.40.run -s --no-drm nvidia-smi
run_unittests: &run_unittests - run: name: Run Unit Tests command: | python -m unittest discover -v -s tests
# -------------------------------------------------------------------------------------# Jobs to run# -------------------------------------------------------------------------------------jobs: cpu_tests: <<: *cpu
working_directory: ~/detectron2
steps: - checkout - <<: *setup_venv
# Cache the venv directory that contains dependencies - restore_cache: keys: - cache-key-{{ .Branch }}-ID-20200425
- <<: *install_dep
- save_cache: paths: - ~/venv key: cache-key-{{ .Branch }}-ID-20200425
- <<: *install_detectron2
- run: name: isort command: | isort -c -sp . - run: name: black command: | black --check -l 100 . - run: name: flake8 command: | flake8 .
- <<: *run_unittests
gpu_tests: <<: *gpu
working_directory: ~/detectron2
steps: - checkout - <<: *install_nvidia_driver
- run: name: Install nvidia-docker working_directory: ~/ command: | curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - distribution=$(. /etc/os-release;echo $ID$VERSION_ID) curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \ sudo tee /etc/apt/sources.list.d/nvidia-docker.list sudo apt-get update && sudo apt-get install -y nvidia-docker2 # reload the docker daemon configuration sudo pkill -SIGHUP dockerd
- run: name: Launch docker working_directory: ~/detectron2/docker command: | nvidia-docker build -t detectron2:v0 -f Dockerfile-circleci . nvidia-docker run -itd --name d2 detectron2:v0 docker exec -it d2 nvidia-smi
- run: name: Build Detectron2 command: | docker exec -it d2 pip install 'git+https://github.com/facebookresearch/fvcore' docker cp ~/detectron2 d2:/detectron2 # This will build d2 for the target GPU arch only docker exec -it d2 pip install -e /detectron2 docker exec -it d2 python3 -m detectron2.utils.collect_env docker exec -it d2 python3 -c 'import torch; assert(torch.cuda.is_available())'
- run: name: Run Unit Tests command: | docker exec -e CIRCLECI=true -it d2 python3 -m unittest discover -v -s /detectron2/tests
workflows: version: 2 regular_test: jobs: - cpu_tests - gpu_tests
#nightly_test: #jobs: #- gpu_tests #triggers: #- schedule: #cron: "0 0 * * *" #filters: #branches: #only: #- master12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485AccessModifierOffset: -1AlignAfterOpenBracket: AlwaysBreakAlignConsecutiveAssignments: falseAlignConsecutiveDeclarations: falseAlignEscapedNewlinesLeft: trueAlignOperands: falseAlignTrailingComments: falseAllowAllParametersOfDeclarationOnNextLine: falseAllowShortBlocksOnASingleLine: falseAllowShortCaseLabelsOnASingleLine: falseAllowShortFunctionsOnASingleLine: EmptyAllowShortIfStatementsOnASingleLine: falseAllowShortLoopsOnASingleLine: falseAlwaysBreakAfterReturnType: NoneAlwaysBreakBeforeMultilineStrings: trueAlwaysBreakTemplateDeclarations: trueBinPackArguments: falseBinPackParameters: falseBraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false BeforeCatch: false BeforeElse: false IndentBraces: falseBreakBeforeBinaryOperators: NoneBreakBeforeBraces: AttachBreakBeforeTernaryOperators: trueBreakConstructorInitializersBeforeComma: falseBreakAfterJavaFieldAnnotations: falseBreakStringLiterals: falseColumnLimit: 80CommentPragmas: '^ IWYU pragma:'ConstructorInitializerAllOnOneLineOrOnePerLine: trueConstructorInitializerIndentWidth: 4ContinuationIndentWidth: 4Cpp11BracedListStyle: trueDerivePointerAlignment: falseDisableFormat: falseForEachMacros: [ FOR_EACH, FOR_EACH_ENUMERATE, FOR_EACH_KV, FOR_EACH_R, FOR_EACH_RANGE, ]IncludeCategories: - Regex: '^<.*\.h(pp)?>' Priority: 1 - Regex: '^<.*' Priority: 2 - Regex: '.*' Priority: 3IndentCaseLabels: trueIndentWidth: 2IndentWrappedFunctionNames: falseKeepEmptyLinesAtTheStartOfBlocks: falseMacroBlockBegin: ''MacroBlockEnd: ''MaxEmptyLinesToKeep: 1NamespaceIndentation: NoneObjCBlockIndentWidth: 2ObjCSpaceAfterProperty: falseObjCSpaceBeforeProtocolList: falsePenaltyBreakBeforeFirstCallParameter: 1PenaltyBreakComment: 300PenaltyBreakFirstLessLess: 120PenaltyBreakString: 1000PenaltyExcessCharacter: 1000000PenaltyReturnTypeOnItsOwnLine: 200PointerAlignment: LeftReflowComments: trueSortIncludes: trueSpaceAfterCStyleCast: falseSpaceBeforeAssignmentOperators: trueSpaceBeforeParens: ControlStatementsSpaceInEmptyParentheses: falseSpacesBeforeTrailingComments: 1SpacesInAngles: falseSpacesInContainerLiterals: trueSpacesInCStyleCastParentheses: falseSpacesInParentheses: falseSpacesInSquareBrackets: falseStandard: Cpp11TabWidth: 8UseTab: Never123456789# This is an example .flake8 config, used when developing *Black* itself.# Keep in sync with setup.cfg which is used for source packages.
[flake8]ignore = W503, E203, E221, C901, C408, E741max-line-length = 100max-complexity = 18select = B,C,E,F,W,T4,B9exclude = build,__init__.py12345# Code of Conduct
Facebook has adopted a Code of Conduct that we expect project participants to adhere to.Please read the [full text](https://code.fb.com/codeofconduct/)so that you can understand what actions will and will not be tolerated.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Contributing to detectron2
## IssuesWe use GitHub issues to track public bugs and questions.Please make sure to follow one of the[issue templates](https://github.com/facebookresearch/detectron2/issues/new/choose)when reporting any issues.
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safedisclosure of security bugs. In those cases, please go through the processoutlined on that page and do not file a public issue.
## Pull RequestsWe actively welcome your pull requests.
However, if you're adding any significant features (e.g. > 50 lines), pleasemake sure to have a corresponding issue to discuss your motivation and proposals,before sending a PR. We do not always accept new features, and we take the followingfactors into consideration:
1. Whether the same feature can be achieved without modifying detectron2.Detectron2 is designed so that you can implement many extensions from the outside, e.g.those in [projects](https://github.com/facebookresearch/detectron2/tree/master/projects).If some part is not as extensible, you can also bring up the issue to make it more extensible.2. Whether the feature is potentially useful to a large audience, or only to a small portion of users.3. Whether the proposed solution has a good design / interface.4. Whether the proposed solution adds extra mental/practical overhead to users who don't need such feature.5. Whether the proposed solution breaks existing APIs.
When sending a PR, please do:
1. If a PR contains multiple orthogonal changes, split it to several PRs.2. If you've added code that should be tested, add tests.3. For PRs that need experiments (e.g. adding a new model or new methods), you don't need to update model zoo, but do provide experiment results in the description of the PR.4. If APIs are changed, update the documentation.5. Make sure your code lints with `./dev/linter.sh`.
## Contributor License Agreement ("CLA")In order to accept your pull request, we need you to submit a CLA. You only needto do this once to work on any of Facebook's open source projects.
Complete your CLA here: <https://code.facebook.com/cla>
## LicenseBy contributing to detectron2, you agree that your contributions will be licensedunder the LICENSE file in the root directory of this source tree.12345
Please select an issue template fromhttps://github.com/facebookresearch/detectron2/issues/new/choose .
Otherwise your issue will be closed.123456789101112131415161718192021222324252627282930313233343536---name: "🐛 Bugs"about: Report bugs in detectron2title: Please read & provide the following
---
## Instructions To Reproduce the 🐛 Bug:
1. what changes you made (`git diff`) or what code you wrote```<put diff or code here>```2. what exact command you run:3. what you observed (including __full logs__):```<put logs here>```4. please simplify the steps as much as possible so they do not require additional resources to run, such as a private dataset.
## Expected behavior:
If there are no obvious error in "what you observed" provided above,please tell us the expected behavior.
## Environment:
Provide your environment information using the following command:```wget -nc -q https://github.com/facebookresearch/detectron2/raw/master/detectron2/utils/collect_env.py && python collect_env.py```
If your issue looks like an installation issue / environment issue,please first try to solve it yourself with the instructions inhttps://detectron2.readthedocs.io/tutorials/install.html#common-installation-issues123456789# require an issue template to be chosenblank_issues_enabled: false
# Unexpected behaviors & bugs are split to two templates.# When they are one template, users think "it's not a bug" and don't choose the template.## But the file name is still "unexpected-problems-bugs.md" so that old references# to this issue template still works.# It's ok since this template should be a superset of "bugs.md" (unexpected behaviors is a superset of bugs)12345678910111213141516171819202122232425262728293031---name: "\U0001F680Feature Request"about: Submit a proposal/request for a new detectron2 feature
---
## 🚀 FeatureA clear and concise description of the feature proposal.
## Motivation & Examples
Tell us why the feature is useful.
Describe what the feature would look like, if it is implemented.Best demonstrated using **code examples** in addition to words.
## Note
We only consider adding new features if they are relevant to many users.
If you request implementation of research papers --we only consider papers that have enough significance and prevalance in the object detection field.
We do not take requests for most projects in the `projects/` directory,because they are research code release that is mainly for other researchers to reproduce results.
Instead of adding features inside detectron2,you can implement many features by [extending detectron2](https://detectron2.readthedocs.io/tutorials/extend.html).The [projects/](https://github.com/facebookresearch/detectron2/tree/master/projects/) directory contains many of such examples.
1234567891011121314151617181920212223242526---name: "❓How to do something?"about: How to do something using detectron2? What does an API do?
---
## ❓ How to do something using detectron2
Describe what you want to do, including:1. what inputs you will provide, if any:2. what outputs you are expecting:
## ❓ What does an API do and how to use it?Please link to which API or documentation you're asking about fromhttps://detectron2.readthedocs.io/
NOTE:
1. Only general answers are provided. If you want to ask about "why X did not work", please use the [Unexpected behaviors](https://github.com/facebookresearch/detectron2/issues/new/choose) issue template.
2. About how to implement new models / new dataloader / new training logic, etc., check documentation first.
3. We do not answer general machine learning / computer vision questions that are not specific to detectron2, such as how a model works, how to improve your training/make it converge, or what algorithm/methods can be used to achieve X.123456789101112131415161718192021222324252627282930313233343536373839404142434445---name: "Unexpected behaviors"about: Run into unexpected behaviors when using detectron2title: Please read & provide the following
---
If you do not know the root cause of the problem, and wish someone to help you, pleasepost according to this template:
## Instructions To Reproduce the Issue:
1. what changes you made (`git diff`) or what code you wrote```<put diff or code here>```2. what exact command you run:3. what you observed (including __full logs__):```<put logs here>```4. please simplify the steps as much as possible so they do not require additional resources to run, such as a private dataset.
## Expected behavior:
If there are no obvious error in "what you observed" provided above,please tell us the expected behavior.
If you expect the model to converge / work better, note that we do not give suggestionson how to train a new model.Only in one of the two conditions we will help with it:(1) You're unable to reproduce the results in detectron2 model zoo.(2) It indicates a detectron2 bug.
## Environment:
Provide your environment information using the following command:```wget -nc -q https://github.com/facebookresearch/detectron2/raw/master/detectron2/utils/collect_env.py && python collect_env.py```
If your issue looks like an installation issue / environment issue,please first try to solve it yourself with the instructions inhttps://detectron2.readthedocs.io/tutorials/install.html#common-installation-issues123456789Thanks for your contribution!
If you're sending a large PR (e.g., >50 lines),please open an issue first about the feature / bug, and indicate how you want to contribute.
Before submitting a PR, please run `dev/linter.sh` to lint the code.
See https://detectron2.readthedocs.io/notes/contributing.html#pull-requestsabout how we handle PRs.12345678910111213141516171819202122232425262728293031323334353637383940414243444546# output diroutputinstant_test_outputinference_test_output
*.jpg*.png*.txt*.json*.diff
# compilation and distribution__pycache___ext*.pyc*.sodetectron2.egg-info/build/dist/wheels/
# pytorch/python/numpy formats*.pth*.pkl*.npy
# ipython/jupyter notebooks*.ipynb**/.ipynb_checkpoints/
# Editor temporaries*.swn*.swo*.swp*~
# editor settings.idea.vscode
# project dirs/detectron2/model_zoo/configs/datasets/projects/*/datasets/models12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879## Getting Started with Detectron2
This document provides a brief intro of the usage of builtin command-line tools in detectron2.
For a tutorial that involves actual coding with the API,see our [Colab Notebook](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5)which covers how to run inference with anexisting model, and how to train a builtin model on a custom dataset.
For more advanced tutorials, refer to our [documentation](https://detectron2.readthedocs.io/tutorials/extend.html).
### Inference Demo with Pre-trained Models
1. Pick a model and its config file from [model zoo](MODEL_ZOO.md), for example, `mask_rcnn_R_50_FPN_3x.yaml`.2. We provide `demo.py` that is able to run builtin standard models. Run it with:```cd demo/python demo.py --config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \ --input input1.jpg input2.jpg \ [--other-options] --opts MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl```The configs are made for training, therefore we need to specify `MODEL.WEIGHTS` to a model from model zoo for evaluation.This command will run the inference and show visualizations in an OpenCV window.
For details of the command line arguments, see `demo.py -h` or look at its source codeto understand its behavior. Some common arguments are:* To run __on your webcam__, replace `--input files` with `--webcam`.* To run __on a video__, replace `--input files` with `--video-input video.mp4`.* To run __on cpu__, add `MODEL.DEVICE cpu` after `--opts`.* To save outputs to a directory (for images) or a file (for webcam or video), use `--output`.
### Training & Evaluation in Command Line
We provide a script in "tools/{,plain_}train_net.py", that is made to trainall the configs provided in detectron2.You may want to use it as a reference to write your own training script.
To train a model with "train_net.py", firstsetup the corresponding datasets following[datasets/README.md](./datasets/README.md),then run:```cd tools/./train_net.py --num-gpus 8 \ --config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml```
The configs are made for 8-GPU training.To train on 1 GPU, you may need to [change some parameters](https://arxiv.org/abs/1706.02677), e.g.:```./train_net.py \ --config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml \ --num-gpus 1 SOLVER.IMS_PER_BATCH 2 SOLVER.BASE_LR 0.0025```
For most models, CPU training is not supported.
To evaluate a model's performance, use```./train_net.py \ --config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml \ --eval-only MODEL.WEIGHTS /path/to/checkpoint_file```For more options, see `./train_net.py -h`.
### Use Detectron2 APIs in Your Code
See our [Colab Notebook](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5)to learn how to use detectron2 APIs to:1. run inference with an existing model2. train a builtin model on a custom dataset
See [detectron2/projects](https://github.com/facebookresearch/detectron2/tree/master/projects)for more ways to build your project on detectron2.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184## Installation
Our [Colab Notebook](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5)has step-by-step instructions that install detectron2.The [Dockerfile](docker)also installs detectron2 with a few simple commands.
### Requirements- Linux or macOS with Python ≥ 3.6- PyTorch ≥ 1.4- [torchvision](https://github.com/pytorch/vision/) that matches the PyTorch installation. You can install them together at [pytorch.org](https://pytorch.org) to make sure of this.- OpenCV, optional, needed by demo and visualization- pycocotools: `pip install cython; pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'`
### Build Detectron2 from Source
gcc & g++ ≥ 5 are required. [ninja](https://ninja-build.org/) is recommended for faster build.After having them, run:```python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'# (add --user if you don't have permission)
# Or, to install it from a local clone:git clone https://github.com/facebookresearch/detectron2.gitpython -m pip install -e detectron2
# Or if you are on macOS# CC=clang CXX=clang++ python -m pip install -e .```
To __rebuild__ detectron2 that's built from a local clone, use `rm -rf build/ **/*.so` to clean theold build first. You often need to rebuild detectron2 after reinstalling PyTorch.
### Install Pre-Built Detectron2 (Linux only)```# for CUDA 10.1:python -m pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/index.html```You can replace cu101 with "cu{100,92}" or "cpu".
Note that:1. Such installation has to be used with certain version of official PyTorch release. See [releases](https://github.com/facebookresearch/detectron2/releases) for requirements. It will not work with a different version of PyTorch or a non-official build of PyTorch.2. Such installation is out-of-date w.r.t. master branch of detectron2. It may not be compatible with the master branch of a research project that uses detectron2 (e.g. those in [projects](projects) or [meshrcnn](https://github.com/facebookresearch/meshrcnn/)).
### Common Installation Issues
If you met issues using the pre-built detectron2, please uninstall it and try building it from source.
Click each issue for its solutions:
<details><summary>Undefined torch/aten/caffe2 symbols, or segmentation fault immediately when running the library.</summary><br/>
This usually happens when detectron2 or torchvision is notcompiled with the version of PyTorch you're running.
Pre-built torchvision or detectron2 has to work with the corresponding official release of pytorch.If the error comes from a pre-built torchvision, uninstall torchvision and pytorch and reinstall themfollowing [pytorch.org](http://pytorch.org). So the versions will match.
If the error comes from a pre-built detectron2, check [release notes](https://github.com/facebookresearch/detectron2/releases)to see the corresponding pytorch version required for each pre-built detectron2.
If the error comes from detectron2 or torchvision that you built manually from source,remove files you built (`build/`, `**/*.so`) and rebuild it so it can pick up the version of pytorch currently in your environment.
If you cannot resolve this problem, please include the output of `gdb -ex "r" -ex "bt" -ex "quit" --args python -m detectron2.utils.collect_env`in your issue.</details>
<details><summary>Undefined C++ symbols (e.g. `GLIBCXX`) or C++ symbols not found.</summary><br/>Usually it's because the library is compiled with a newer C++ compiler but run with an old C++ runtime.
This often happens with old anaconda.Try `conda update libgcc`. Then rebuild detectron2.
The fundamental solution is to run the code with proper C++ runtime.One way is to use `LD_PRELOAD=/path/to/libstdc++.so`.
</details>
<details><summary>"Not compiled with GPU support" or "Detectron2 CUDA Compiler: not available".</summary><br/>CUDA is not found when building detectron2.You should make sure
```python -c 'import torch; from torch.utils.cpp_extension import CUDA_HOME; print(torch.cuda.is_available(), CUDA_HOME)'```
print valid outputs at the time you build detectron2.
Most models can run inference (but not training) without GPU support. To use CPUs, set `MODEL.DEVICE='cpu'` in the config.</details>
<details><summary>"invalid device function" or "no kernel image is available for execution".</summary><br/>Two possibilities:
* You build detectron2 with one version of CUDA but run it with a different version.
To check whether it is the case, use `python -m detectron2.utils.collect_env` to find out inconsistent CUDA versions. In the output of this command, you should expect "Detectron2 CUDA Compiler", "CUDA_HOME", "PyTorch built with - CUDA" to contain cuda libraries of the same version.
When they are inconsistent, you need to either install a different build of PyTorch (or build by yourself) to match your local CUDA installation, or install a different version of CUDA to match PyTorch.
* Detectron2 or PyTorch/torchvision is not built for the correct GPU architecture (compute compatibility).
The GPU architecture for PyTorch/detectron2/torchvision is available in the "architecture flags" in `python -m detectron2.utils.collect_env`.
The GPU architecture flags of detectron2/torchvision by default matches the GPU model detected during compilation. This means the compiled code may not work on a different GPU model. To overwrite the GPU architecture for detectron2/torchvision, use `TORCH_CUDA_ARCH_LIST` environment variable during compilation.
For example, `export TORCH_CUDA_ARCH_LIST=6.0,7.0` makes it compile for both P100s and V100s. Visit [developer.nvidia.com/cuda-gpus](https://developer.nvidia.com/cuda-gpus) to find out the correct compute compatibility number for your device.
</details>
<details><summary>Undefined CUDA symbols; cannot open libcudart.so; other nvcc failures.</summary><br/>The version of NVCC you use to build detectron2 or torchvision doesnot match the version of CUDA you are running with.This often happens when using anaconda's CUDA runtime.
Use `python -m detectron2.utils.collect_env` to find out inconsistent CUDA versions.In the output of this command, you should expect "Detectron2 CUDA Compiler", "CUDA_HOME", "PyTorch built with - CUDA"to contain cuda libraries of the same version.
When they are inconsistent,you need to either install a different build of PyTorch (or build by yourself)to match your local CUDA installation, or install a different version of CUDA to match PyTorch.</details>
<details><summary>"ImportError: cannot import name '_C'".</summary><br/>Please build and install detectron2 following the instructions above.
If you are running code from detectron2's root directory, `cd` to a different one.Otherwise you may not import the code that you installed.</details>
<details><summary>ONNX conversion segfault after some "TraceWarning".</summary><br/>The ONNX package is compiled with too old compiler.
Please build and install ONNX from its source code using a compilerwhose version is closer to what's used by PyTorch (available in `torch.__config__.show()`).</details>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized bythe copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and allother entities that control, are controlled by, or are under commoncontrol with that entity. For the purposes of this definition,"control" means (i) the power, direct or indirect, to cause thedirection or management of such entity, whether by contract orotherwise, or (ii) ownership of fifty percent (50%) or more of theoutstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entityexercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,including but not limited to software source code, documentationsource, and configuration files.
"Object" form shall mean any form resulting from mechanicaltransformation or translation of a Source form, including butnot limited to compiled object code, generated documentation,and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source orObject form, made available under the License, as indicated by acopyright notice that is included in or attached to the work(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Objectform, that is based on (or derived from) the Work and for which theeditorial revisions, annotations, elaborations, or other modificationsrepresent, as a whole, an original work of authorship. For the purposesof this License, Derivative Works shall not include works that remainseparable from, or merely link (or bind by name) to the interfaces of,the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, includingthe original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of theWork or Derivative Works thereof in any medium, with or withoutmodifications, and in Source or Object form, provided that Youmeet the following conditions:
(a) You must give any other recipients of the Work orDerivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent noticesstating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Worksthat You distribute, all copyright, patent, trademark, andattribution notices from the Source form of the Work,excluding those notices that do not pertain to any part ofthe Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of itsdistribution, then any Derivative Works that You distribute mustinclude a readable copy of the attribution notices containedwithin such NOTICE file, excluding those notices that do notpertain to any part of the Derivative Works, in at least oneof the following places: within a NOTICE text file distributedas part of the Derivative Works; within the Source form ordocumentation, if provided along with the Derivative Works; or,within a display generated by the Derivative Works, if andwherever such third-party notices normally appear. The contentsof the NOTICE file are for informational purposes only anddo not modify the License. You may add Your own attributionnotices within Derivative Works that You distribute, alongsideor as an addendum to the NOTICE text from the Work, providedthat such additional attribution notices cannot be construedas modifying the License.
You may add Your own copyright statement to Your modifications andmay provide additional or different license terms and conditionsfor use, reproduction, or distribution of Your modifications, orfor any such Derivative Works as a whole, provided Your use,reproduction, and distribution of the Work otherwise complies withthe conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,any Contribution intentionally submitted for inclusion in the Workby You to the Licensor shall be under the terms and conditions ofthis License, without any additional terms or conditions.Notwithstanding the above, nothing herein shall supersede or modifythe terms of any separate license agreement you may have executedwith Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the tradenames, trademarks, service marks, or product names of the Licensor,except as required for reasonable and customary use in describing theorigin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law oragreed to in writing, Licensor provides the Work (and eachContributor provides its Contributions) on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied, including, without limitation, any warranties or conditionsof TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR APARTICULAR PURPOSE. You are solely responsible for determining theappropriateness of using or redistributing the Work and assume anyrisks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,whether in tort (including negligence), contract, or otherwise,unless required by applicable law (such as deliberate and grosslynegligent acts) or agreed to in writing, shall any Contributor beliable to You for damages, including any direct, indirect, special,incidental, or consequential damages of any character arising as aresult of this License or out of the use or inability to use theWork (including but not limited to damages for loss of goodwill,work stoppage, computer failure or malfunction, or any and allother commercial damages or losses), even if such Contributorhas been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributingthe Work or Derivative Works thereof, You may choose to offer,and charge a fee for, acceptance of support, warranty, indemnity,or other liability obligations and/or rights consistent with thisLicense. However, in accepting such obligations, You may act onlyon Your own behalf and on Your sole responsibility, not on behalfof any other Contributor, and only if You agree to indemnify,defend, and hold each Contributor harmless for any liabilityincurred by, or claims asserted against, such Contributor by reasonof your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the followingboilerplate notice, with the fields enclosed by brackets "[]"replaced with your own identifying information. (Don't includethe brackets!) The text should be enclosed in the appropriatecomment syntax for the file format. We also recommend that afile or class name and description of purpose be included on thesame "printed page" as the copyright notice for easieridentification within third-party archives.
Copyright 2019 - present, Facebook, Inc
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903# Detectron2 Model Zoo and Baselines
## Introduction
This file documents a large collection of baselines trainedwith detectron2 in Sep-Oct, 2019.All numbers were obtained on [Big Basin](https://engineering.fb.com/data-center-engineering/introducing-big-basin-our-next-generation-ai-hardware/)servers with 8 NVIDIA V100 GPUs & NVLink. The software in use were PyTorch 1.3, CUDA 9.2, cuDNN 7.4.2 or 7.6.3.You can access these models from code using [detectron2.model_zoo](https://detectron2.readthedocs.io/modules/model_zoo.html) APIs.
In addition to these official baseline models, you can find more models in [projects/](projects/).
#### How to Read the Tables* The "Name" column contains a link to the config file. Running `tools/train_net.py` with this config file and 8 GPUs will reproduce the model.* Training speed is averaged across the entire training. We keep updating the speed with latest version of detectron2/pytorch/etc., so they might be different from the `metrics` file. Training speed for multi-machine jobs is not provided.* Inference speed is measured by `tools/train_net.py --eval-only`, or [inference_on_dataset()](https://detectron2.readthedocs.io/modules/evaluation.html#detectron2.evaluation.inference_on_dataset), with batch size 1 in detectron2 directly. Measuring it with your own code will likely introduce other overhead. Actual deployment in production should in general be faster than the given inference speed due to more optimizations.* The *model id* column is provided for ease of reference. To check downloaded file integrity, any model on this page contains its md5 prefix in its file name.* Training curves and other statistics can be found in `metrics` for each model.
#### Common Settings for COCO Models* All COCO models were trained on `train2017` and evaluated on `val2017`.* The default settings are __not directly comparable__ with Detectron's standard settings. For example, our default training data augmentation uses scale jittering in addition to horizontal flipping.
To make fair comparisons with Detectron's settings, see [Detectron1-Comparisons](configs/Detectron1-Comparisons/) for accuracy comparison, and [benchmarks](https://detectron2.readthedocs.io/notes/benchmarks.html) for speed comparison.* For Faster/Mask R-CNN, we provide baselines based on __3 different backbone combinations__: * __FPN__: Use a ResNet+FPN backbone with standard conv and FC heads for mask and box prediction, respectively. It obtains the best speed/accuracy tradeoff, but the other two are still useful for research. * __C4__: Use a ResNet conv4 backbone with conv5 head. The original baseline in the Faster R-CNN paper. * __DC5__ (Dilated-C5): Use a ResNet conv5 backbone with dilations in conv5, and standard conv and FC heads for mask and box prediction, respectively. This is used by the Deformable ConvNet paper.* Most models are trained with the 3x schedule (~37 COCO epochs). Although 1x models are heavily under-trained, we provide some ResNet-50 models with the 1x (~12 COCO epochs) training schedule for comparison when doing quick research iteration.
#### ImageNet Pretrained Models
We provide backbone models pretrained on ImageNet-1k dataset.These models have __different__ format from those provided in Detectron: we do not fuse BatchNorm into an affine layer.* [R-50.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-50.pkl): converted copy of [MSRA's original ResNet-50](https://github.com/KaimingHe/deep-residual-networks) model.* [R-101.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-101.pkl): converted copy of [MSRA's original ResNet-101](https://github.com/KaimingHe/deep-residual-networks) model.* [X-101-32x8d.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/FAIR/X-101-32x8d.pkl): ResNeXt-101-32x8d model trained with Caffe2 at FB.
Pretrained models in Detectron's format can still be used. For example:* [X-152-32x8d-IN5k.pkl](https://dl.fbaipublicfiles.com/detectron/ImageNetPretrained/25093814/X-152-32x8d-IN5k.pkl): ResNeXt-152-32x8d model trained on ImageNet-5k with Caffe2 at FB (see ResNeXt paper for details on ImageNet-5k).* [R-50-GN.pkl](https://dl.fbaipublicfiles.com/detectron/ImageNetPretrained/47261647/R-50-GN.pkl): ResNet-50 with Group Normalization.* [R-101-GN.pkl](https://dl.fbaipublicfiles.com/detectron/ImageNetPretrained/47592356/R-101-GN.pkl): ResNet-101 with Group Normalization.
Torchvision's ResNet models can be used after converted by [this script](tools/convert-torchvision-to-d2.py).
#### License
All models available for download through this document are licensed under the[Creative Commons Attribution-ShareAlike 3.0 license](https://creativecommons.org/licenses/by-sa/3.0/).
### COCO Object Detection Baselines
#### Faster R-CNN:<!--(fb only) To update the table in vim:1. Remove the old table: d}2. Copy the below command to the place of the table3. :.!bash
./gen_html_table.py --config 'COCO-Detection/faster*50*'{1x,3x}'*' 'COCO-Detection/faster*101*' --name R50-C4 R50-DC5 R50-FPN R50-C4 R50-DC5 R50-FPN R101-C4 R101-DC5 R101-FPN X101-FPN --fields lr_sched train_speed inference_speed mem box_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: faster_rcnn_R_50_C4_1x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_C4_1x.yaml">R50-C4</a></td><td align="center">1x</td><td align="center">0.551</td><td align="center">0.102</td><td align="center">4.8</td><td align="center">35.7</td><td align="center">137257644</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_C4_1x/137257644/model_final_721ade.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_C4_1x/137257644/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_DC5_1x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_DC5_1x.yaml">R50-DC5</a></td><td align="center">1x</td><td align="center">0.380</td><td align="center">0.068</td><td align="center">5.0</td><td align="center">37.3</td><td align="center">137847829</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_DC5_1x/137847829/model_final_51d356.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_DC5_1x/137847829/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml">R50-FPN</a></td><td align="center">1x</td><td align="center">0.210</td><td align="center">0.038</td><td align="center">3.0</td><td align="center">37.9</td><td align="center">137257794</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_FPN_1x/137257794/model_final_b275ba.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_FPN_1x/137257794/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_C4_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_C4_3x.yaml">R50-C4</a></td><td align="center">3x</td><td align="center">0.543</td><td align="center">0.104</td><td align="center">4.8</td><td align="center">38.4</td><td align="center">137849393</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_C4_3x/137849393/model_final_f97cb7.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_C4_3x/137849393/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_DC5_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_DC5_3x.yaml">R50-DC5</a></td><td align="center">3x</td><td align="center">0.378</td><td align="center">0.070</td><td align="center">5.0</td><td align="center">39.0</td><td align="center">137849425</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_DC5_3x/137849425/model_final_68d202.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_DC5_3x/137849425/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml">R50-FPN</a></td><td align="center">3x</td><td align="center">0.209</td><td align="center">0.038</td><td align="center">3.0</td><td align="center">40.2</td><td align="center">137849458</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_FPN_3x/137849458/model_final_280758.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_50_FPN_3x/137849458/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_101_C4_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_101_C4_3x.yaml">R101-C4</a></td><td align="center">3x</td><td align="center">0.619</td><td align="center">0.139</td><td align="center">5.9</td><td align="center">41.1</td><td align="center">138204752</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_C4_3x/138204752/model_final_298dad.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_C4_3x/138204752/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_101_DC5_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_101_DC5_3x.yaml">R101-DC5</a></td><td align="center">3x</td><td align="center">0.452</td><td align="center">0.086</td><td align="center">6.1</td><td align="center">40.6</td><td align="center">138204841</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_DC5_3x/138204841/model_final_3e0943.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_DC5_3x/138204841/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_101_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml">R101-FPN</a></td><td align="center">3x</td><td align="center">0.286</td><td align="center">0.051</td><td align="center">4.1</td><td align="center">42.0</td><td align="center">137851257</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_FPN_3x/137851257/model_final_f6e8b1.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_R_101_FPN_3x/137851257/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_X_101_32x8d_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml">X101-FPN</a></td><td align="center">3x</td><td align="center">0.638</td><td align="center">0.098</td><td align="center">6.7</td><td align="center">43.0</td><td align="center">139173657</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x/139173657/model_final_68b088.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x/139173657/metrics.json">metrics</a></td></tr></tbody></table>
#### RetinaNet:<!--./gen_html_table.py --config 'COCO-Detection/retina*50*' 'COCO-Detection/retina*101*' --name R50 R50 R101 --fields lr_sched train_speed inference_speed mem box_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: retinanet_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml">R50</a></td><td align="center">1x</td><td align="center">0.200</td><td align="center">0.055</td><td align="center">3.9</td><td align="center">36.5</td><td align="center">137593951</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_50_FPN_1x/137593951/model_final_b796dc.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_50_FPN_1x/137593951/metrics.json">metrics</a></td></tr><!-- ROW: retinanet_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Detection/retinanet_R_50_FPN_3x.yaml">R50</a></td><td align="center">3x</td><td align="center">0.201</td><td align="center">0.055</td><td align="center">3.9</td><td align="center">37.9</td><td align="center">137849486</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_50_FPN_3x/137849486/model_final_4cafe0.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_50_FPN_3x/137849486/metrics.json">metrics</a></td></tr><!-- ROW: retinanet_R_101_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Detection/retinanet_R_101_FPN_3x.yaml">R101</a></td><td align="center">3x</td><td align="center">0.280</td><td align="center">0.068</td><td align="center">5.1</td><td align="center">39.9</td><td align="center">138363263</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_101_FPN_3x/138363263/model_final_59f53c.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/retinanet_R_101_FPN_3x/138363263/metrics.json">metrics</a></td></tr></tbody></table>
#### RPN & Fast R-CNN:<!--./gen_html_table.py --config 'COCO-Detection/rpn*' 'COCO-Detection/fast_rcnn*' --name "RPN R50-C4" "RPN R50-FPN" "Fast R-CNN R50-FPN" --fields lr_sched train_speed inference_speed mem box_AP prop_AR-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">prop.<br/>AR</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: rpn_R_50_C4_1x --> <tr><td align="left"><a href="configs/COCO-Detection/rpn_R_50_C4_1x.yaml">RPN R50-C4</a></td><td align="center">1x</td><td align="center">0.130</td><td align="center">0.034</td><td align="center">1.5</td><td align="center"></td><td align="center">51.6</td><td align="center">137258005</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/rpn_R_50_C4_1x/137258005/model_final_450694.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/rpn_R_50_C4_1x/137258005/metrics.json">metrics</a></td></tr><!-- ROW: rpn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-Detection/rpn_R_50_FPN_1x.yaml">RPN R50-FPN</a></td><td align="center">1x</td><td align="center">0.186</td><td align="center">0.032</td><td align="center">2.7</td><td align="center"></td><td align="center">58.0</td><td align="center">137258492</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/rpn_R_50_FPN_1x/137258492/model_final_02ce48.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/rpn_R_50_FPN_1x/137258492/metrics.json">metrics</a></td></tr><!-- ROW: fast_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-Detection/fast_rcnn_R_50_FPN_1x.yaml">Fast R-CNN R50-FPN</a></td><td align="center">1x</td><td align="center">0.140</td><td align="center">0.029</td><td align="center">2.6</td><td align="center">37.8</td><td align="center"></td><td align="center">137635226</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/fast_rcnn_R_50_FPN_1x/137635226/model_final_e5f7ce.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Detection/fast_rcnn_R_50_FPN_1x/137635226/metrics.json">metrics</a></td></tr></tbody></table>
### COCO Instance Segmentation Baselines with Mask R-CNN<!--./gen_html_table.py --config 'COCO-InstanceSegmentation/mask*50*'{1x,3x}'*' 'COCO-InstanceSegmentation/mask*101*' --name R50-C4 R50-DC5 R50-FPN R50-C4 R50-DC5 R50-FPN R101-C4 R101-DC5 R101-FPN X101-FPN --fields lr_sched train_speed inference_speed mem box_AP mask_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: mask_rcnn_R_50_C4_1x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x.yaml">R50-C4</a></td><td align="center">1x</td><td align="center">0.584</td><td align="center">0.110</td><td align="center">5.2</td><td align="center">36.8</td><td align="center">32.2</td><td align="center">137259246</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x/137259246/model_final_9243eb.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x/137259246/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_DC5_1x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x.yaml">R50-DC5</a></td><td align="center">1x</td><td align="center">0.471</td><td align="center">0.076</td><td align="center">6.5</td><td align="center">38.3</td><td align="center">34.2</td><td align="center">137260150</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x/137260150/model_final_4f86c3.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x/137260150/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml">R50-FPN</a></td><td align="center">1x</td><td align="center">0.261</td><td align="center">0.043</td><td align="center">3.4</td><td align="center">38.6</td><td align="center">35.2</td><td align="center">137260431</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_C4_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x.yaml">R50-C4</a></td><td align="center">3x</td><td align="center">0.575</td><td align="center">0.111</td><td align="center">5.2</td><td align="center">39.8</td><td align="center">34.4</td><td align="center">137849525</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x/137849525/model_final_4ce675.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x/137849525/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_DC5_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x.yaml">R50-DC5</a></td><td align="center">3x</td><td align="center">0.470</td><td align="center">0.076</td><td align="center">6.5</td><td align="center">40.0</td><td align="center">35.9</td><td align="center">137849551</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x/137849551/model_final_84107b.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x/137849551/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml">R50-FPN</a></td><td align="center">3x</td><td align="center">0.261</td><td align="center">0.043</td><td align="center">3.4</td><td align="center">41.0</td><td align="center">37.2</td><td align="center">137849600</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_101_C4_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x.yaml">R101-C4</a></td><td align="center">3x</td><td align="center">0.652</td><td align="center">0.145</td><td align="center">6.3</td><td align="center">42.6</td><td align="center">36.7</td><td align="center">138363239</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x/138363239/model_final_a2914c.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x/138363239/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_101_DC5_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x.yaml">R101-DC5</a></td><td align="center">3x</td><td align="center">0.545</td><td align="center">0.092</td><td align="center">7.6</td><td align="center">41.9</td><td align="center">37.3</td><td align="center">138363294</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x/138363294/model_final_0464b7.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x/138363294/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_101_FPN_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml">R101-FPN</a></td><td align="center">3x</td><td align="center">0.340</td><td align="center">0.056</td><td align="center">4.6</td><td align="center">42.9</td><td align="center">38.6</td><td align="center">138205316</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x/138205316/model_final_a3ec72.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x/138205316/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_X_101_32x8d_FPN_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml">X101-FPN</a></td><td align="center">3x</td><td align="center">0.690</td><td align="center">0.103</td><td align="center">7.2</td><td align="center">44.3</td><td align="center">39.5</td><td align="center">139653917</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x/139653917/model_final_2d9806.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x/139653917/metrics.json">metrics</a></td></tr></tbody></table>
### COCO Person Keypoint Detection Baselines with Keypoint R-CNN<!--./gen_html_table.py --config 'COCO-Keypoints/*50*' 'COCO-Keypoints/*101*' --name R50-FPN R50-FPN R101-FPN X101-FPN --fields lr_sched train_speed inference_speed mem box_AP keypoint_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">kp.<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: keypoint_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.yaml">R50-FPN</a></td><td align="center">1x</td><td align="center">0.315</td><td align="center">0.072</td><td align="center">5.0</td><td align="center">53.6</td><td align="center">64.0</td><td align="center">137261548</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x/137261548/model_final_04e291.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x/137261548/metrics.json">metrics</a></td></tr><!-- ROW: keypoint_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml">R50-FPN</a></td><td align="center">3x</td><td align="center">0.316</td><td align="center">0.066</td><td align="center">5.0</td><td align="center">55.4</td><td align="center">65.5</td><td align="center">137849621</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x/137849621/model_final_a6e10b.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x/137849621/metrics.json">metrics</a></td></tr><!-- ROW: keypoint_rcnn_R_101_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x.yaml">R101-FPN</a></td><td align="center">3x</td><td align="center">0.390</td><td align="center">0.076</td><td align="center">6.1</td><td align="center">56.4</td><td align="center">66.1</td><td align="center">138363331</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x/138363331/model_final_997cc7.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x/138363331/metrics.json">metrics</a></td></tr><!-- ROW: keypoint_rcnn_X_101_32x8d_FPN_3x --> <tr><td align="left"><a href="configs/COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x.yaml">X101-FPN</a></td><td align="center">3x</td><td align="center">0.738</td><td align="center">0.121</td><td align="center">8.7</td><td align="center">57.3</td><td align="center">66.0</td><td align="center">139686956</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x/139686956/model_final_5ad38f.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x/139686956/metrics.json">metrics</a></td></tr></tbody></table>
### COCO Panoptic Segmentation Baselines with Panoptic FPN<!--./gen_html_table.py --config 'COCO-PanopticSegmentation/*50*' 'COCO-PanopticSegmentation/*101*' --name R50-FPN R50-FPN R101-FPN --fields lr_sched train_speed inference_speed mem box_AP mask_AP PQ-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">PQ</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: panoptic_fpn_R_50_1x --> <tr><td align="left"><a href="configs/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x.yaml">R50-FPN</a></td><td align="center">1x</td><td align="center">0.304</td><td align="center">0.053</td><td align="center">4.8</td><td align="center">37.6</td><td align="center">34.7</td><td align="center">39.4</td><td align="center">139514544</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x/139514544/model_final_dbfeb4.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x/139514544/metrics.json">metrics</a></td></tr><!-- ROW: panoptic_fpn_R_50_3x --> <tr><td align="left"><a href="configs/COCO-PanopticSegmentation/panoptic_fpn_R_50_3x.yaml">R50-FPN</a></td><td align="center">3x</td><td align="center">0.302</td><td align="center">0.053</td><td align="center">4.8</td><td align="center">40.0</td><td align="center">36.5</td><td align="center">41.5</td><td align="center">139514569</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_50_3x/139514569/model_final_c10459.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_50_3x/139514569/metrics.json">metrics</a></td></tr><!-- ROW: panoptic_fpn_R_101_3x --> <tr><td align="left"><a href="configs/COCO-PanopticSegmentation/panoptic_fpn_R_101_3x.yaml">R101-FPN</a></td><td align="center">3x</td><td align="center">0.392</td><td align="center">0.066</td><td align="center">6.0</td><td align="center">42.4</td><td align="center">38.5</td><td align="center">43.0</td><td align="center">139514519</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_101_3x/139514519/model_final_cafdb1.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_101_3x/139514519/metrics.json">metrics</a></td></tr></tbody></table>
### LVIS Instance Segmentation Baselines with Mask R-CNN
Mask R-CNN baselines on the [LVIS dataset](https://lvisdataset.org), v0.5.These baselines are described in Table 3(c) of the [LVIS paper](https://arxiv.org/abs/1908.03195).
NOTE: the 1x schedule here has the same amount of __iterations__ as the COCO 1x baselines.They are roughly 24 epochs of LVISv0.5 data.The final results of these configs have large variance across different runs.
<!--./gen_html_table.py --config 'LVIS-InstanceSegmentation/mask*50*' 'LVIS-InstanceSegmentation/mask*101*' --name R50-FPN R101-FPN X101-FPN --fields lr_sched train_speed inference_speed mem box_AP mask_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: mask_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/LVIS-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml">R50-FPN</a></td><td align="center">1x</td><td align="center">0.292</td><td align="center">0.107</td><td align="center">7.1</td><td align="center">23.6</td><td align="center">24.4</td><td align="center">144219072</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/144219072/model_final_571f7c.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/144219072/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_101_FPN_1x --> <tr><td align="left"><a href="configs/LVIS-InstanceSegmentation/mask_rcnn_R_101_FPN_1x.yaml">R101-FPN</a></td><td align="center">1x</td><td align="center">0.371</td><td align="center">0.114</td><td align="center">7.8</td><td align="center">25.6</td><td align="center">25.9</td><td align="center">144219035</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_R_101_FPN_1x/144219035/model_final_824ab5.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_R_101_FPN_1x/144219035/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_X_101_32x8d_FPN_1x --> <tr><td align="left"><a href="configs/LVIS-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml">X101-FPN</a></td><td align="center">1x</td><td align="center">0.712</td><td align="center">0.151</td><td align="center">10.2</td><td align="center">26.7</td><td align="center">27.1</td><td align="center">144219108</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x/144219108/model_final_5e3439.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/LVIS-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x/144219108/metrics.json">metrics</a></td></tr></tbody></table>
### Cityscapes & Pascal VOC Baselines
Simple baselines for* Mask R-CNN on Cityscapes instance segmentation (initialized from COCO pre-training, then trained on Cityscapes fine annotations only)* Faster R-CNN on PASCAL VOC object detection (trained on VOC 2007 train+val + VOC 2012 train+val, tested on VOC 2007 using 11-point interpolated AP)
<!--./gen_html_table.py --config 'Cityscapes/*' 'PascalVOC-Detection/*' --name "R50-FPN, Cityscapes" "R50-C4, VOC" --fields train_speed inference_speed mem box_AP box_AP50 mask_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">box<br/>AP50</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: mask_rcnn_R_50_FPN --> <tr><td align="left"><a href="configs/Cityscapes/mask_rcnn_R_50_FPN.yaml">R50-FPN, Cityscapes</a></td><td align="center">0.240</td><td align="center">0.078</td><td align="center">4.4</td><td align="center"></td><td align="center"></td><td align="center">36.5</td><td align="center">142423278</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Cityscapes/mask_rcnn_R_50_FPN/142423278/model_final_af9cf5.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Cityscapes/mask_rcnn_R_50_FPN/142423278/metrics.json">metrics</a></td></tr><!-- ROW: faster_rcnn_R_50_C4 --> <tr><td align="left"><a href="configs/PascalVOC-Detection/faster_rcnn_R_50_C4.yaml">R50-C4, VOC</a></td><td align="center">0.537</td><td align="center">0.081</td><td align="center">4.8</td><td align="center">51.9</td><td align="center">80.3</td><td align="center"></td><td align="center">142202221</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/PascalVOC-Detection/faster_rcnn_R_50_C4/142202221/model_final_b1acc2.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/PascalVOC-Detection/faster_rcnn_R_50_C4/142202221/metrics.json">metrics</a></td></tr></tbody></table>
### Other Settings
Ablations for Deformable Conv and Cascade R-CNN:
<!--./gen_html_table.py --config 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml' 'Misc/*R_50_FPN_1x_dconv*' 'Misc/cascade*1x.yaml' 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml' 'Misc/*R_50_FPN_3x_dconv*' 'Misc/cascade*3x.yaml' --name "Baseline R50-FPN" "Deformable Conv" "Cascade R-CNN" "Baseline R50-FPN" "Deformable Conv" "Cascade R-CNN" --fields lr_sched train_speed inference_speed mem box_AP mask_AP-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: mask_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml">Baseline R50-FPN</a></td><td align="center">1x</td><td align="center">0.261</td><td align="center">0.043</td><td align="center">3.4</td><td align="center">38.6</td><td align="center">35.2</td><td align="center">137260431</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_1x_dconv_c3-c5 --> <tr><td align="left"><a href="configs/Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5.yaml">Deformable Conv</a></td><td align="center">1x</td><td align="center">0.342</td><td align="center">0.048</td><td align="center">3.5</td><td align="center">41.5</td><td align="center">37.5</td><td align="center">138602867</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5/138602867/model_final_65c703.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5/138602867/metrics.json">metrics</a></td></tr><!-- ROW: cascade_mask_rcnn_R_50_FPN_1x --> <tr><td align="left"><a href="configs/Misc/cascade_mask_rcnn_R_50_FPN_1x.yaml">Cascade R-CNN</a></td><td align="center">1x</td><td align="center">0.317</td><td align="center">0.052</td><td align="center">4.0</td><td align="center">42.1</td><td align="center">36.4</td><td align="center">138602847</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_R_50_FPN_1x/138602847/model_final_e9d89b.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_R_50_FPN_1x/138602847/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml">Baseline R50-FPN</a></td><td align="center">3x</td><td align="center">0.261</td><td align="center">0.043</td><td align="center">3.4</td><td align="center">41.0</td><td align="center">37.2</td><td align="center">137849600</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_3x_dconv_c3-c5 --> <tr><td align="left"><a href="configs/Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5.yaml">Deformable Conv</a></td><td align="center">3x</td><td align="center">0.349</td><td align="center">0.047</td><td align="center">3.5</td><td align="center">42.7</td><td align="center">38.5</td><td align="center">144998336</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5/144998336/model_final_821d0b.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5/144998336/metrics.json">metrics</a></td></tr><!-- ROW: cascade_mask_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/Misc/cascade_mask_rcnn_R_50_FPN_3x.yaml">Cascade R-CNN</a></td><td align="center">3x</td><td align="center">0.328</td><td align="center">0.053</td><td align="center">4.0</td><td align="center">44.3</td><td align="center">38.5</td><td align="center">144998488</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_R_50_FPN_3x/144998488/model_final_480dd8.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_R_50_FPN_3x/144998488/metrics.json">metrics</a></td></tr></tbody></table>
Ablations for normalization methods, and a few models trained from scratch following [Rethinking ImageNet Pre-training](https://arxiv.org/abs/1811.08883).(Note: The baseline uses `2fc` head while the others use [`4conv1fc` head](https://arxiv.org/abs/1803.08494))<!--./gen_html_table.py --config 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml' 'Misc/mask*50_FPN_3x_gn.yaml' 'Misc/mask*50_FPN_3x_syncbn.yaml' 'Misc/scratch*' --name "Baseline R50-FPN" "GN" "SyncBN" "GN (from scratch)" "GN (from scratch)" "SyncBN (from scratch)" --fields lr_sched train_speed inference_speed mem box_AP mask_AP -->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">lr<br/>sched</th><th valign="bottom">train<br/>time<br/>(s/iter)</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: mask_rcnn_R_50_FPN_3x --> <tr><td align="left"><a href="configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml">Baseline R50-FPN</a></td><td align="center">3x</td><td align="center">0.261</td><td align="center">0.043</td><td align="center">3.4</td><td align="center">41.0</td><td align="center">37.2</td><td align="center">137849600</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_3x_gn --> <tr><td align="left"><a href="configs/Misc/mask_rcnn_R_50_FPN_3x_gn.yaml">GN</a></td><td align="center">3x</td><td align="center">0.356</td><td align="center">0.069</td><td align="center">7.3</td><td align="center">42.6</td><td align="center">38.6</td><td align="center">138602888</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_gn/138602888/model_final_dc5d9e.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_gn/138602888/metrics.json">metrics</a></td></tr><!-- ROW: mask_rcnn_R_50_FPN_3x_syncbn --> <tr><td align="left"><a href="configs/Misc/mask_rcnn_R_50_FPN_3x_syncbn.yaml">SyncBN</a></td><td align="center">3x</td><td align="center">0.371</td><td align="center">0.053</td><td align="center">5.5</td><td align="center">41.9</td><td align="center">37.8</td><td align="center">169527823</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_syncbn/169527823/model_final_3b3c51.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/mask_rcnn_R_50_FPN_3x_syncbn/169527823/metrics.json">metrics</a></td></tr><!-- ROW: scratch_mask_rcnn_R_50_FPN_3x_gn --> <tr><td align="left"><a href="configs/Misc/scratch_mask_rcnn_R_50_FPN_3x_gn.yaml">GN (from scratch)</a></td><td align="center">3x</td><td align="center">0.400</td><td align="center">0.069</td><td align="center">9.8</td><td align="center">39.9</td><td align="center">36.6</td><td align="center">138602908</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_3x_gn/138602908/model_final_01ca85.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_3x_gn/138602908/metrics.json">metrics</a></td></tr><!-- ROW: scratch_mask_rcnn_R_50_FPN_9x_gn --> <tr><td align="left"><a href="configs/Misc/scratch_mask_rcnn_R_50_FPN_9x_gn.yaml">GN (from scratch)</a></td><td align="center">9x</td><td align="center">N/A</td><td align="center">0.070</td><td align="center">9.8</td><td align="center">43.7</td><td align="center">39.6</td><td align="center">183808979</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_9x_gn/183808979/model_final_da7b4c.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_9x_gn/183808979/metrics.json">metrics</a></td></tr><!-- ROW: scratch_mask_rcnn_R_50_FPN_9x_syncbn --> <tr><td align="left"><a href="configs/Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn.yaml">SyncBN (from scratch)</a></td><td align="center">9x</td><td align="center">N/A</td><td align="center">0.055</td><td align="center">7.2</td><td align="center">43.6</td><td align="center">39.3</td><td align="center">184226666</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn/184226666/model_final_5ce33e.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn/184226666/metrics.json">metrics</a></td></tr></tbody></table>
A few very large models trained for a long time, for demo purposes. They are trained using multiple machines:
<!--./gen_html_table.py --config 'Misc/panoptic_*dconv*' 'Misc/cascade_*152*' --name "Panoptic FPN R101" "Mask R-CNN X152" --fields inference_speed mem box_AP mask_AP PQ# manually add TTA results-->
<table><tbody><!-- START TABLE --><!-- TABLE HEADER --><th valign="bottom">Name</th><th valign="bottom">inference<br/>time<br/>(s/im)</th><th valign="bottom">train<br/>mem<br/>(GB)</th><th valign="bottom">box<br/>AP</th><th valign="bottom">mask<br/>AP</th><th valign="bottom">PQ</th><th valign="bottom">model id</th><th valign="bottom">download</th><!-- TABLE BODY --><!-- ROW: panoptic_fpn_R_101_dconv_cascade_gn_3x --> <tr><td align="left"><a href="configs/Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x.yaml">Panoptic FPN R101</a></td><td align="center">0.107</td><td align="center">11.4</td><td align="center">47.4</td><td align="center">41.3</td><td align="center">46.1</td><td align="center">139797668</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x/139797668/model_final_be35db.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x/139797668/metrics.json">metrics</a></td></tr><!-- ROW: cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv --> <tr><td align="left"><a href="configs/Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv.yaml">Mask R-CNN X152</a></td><td align="center">0.242</td><td align="center">15.1</td><td align="center">50.2</td><td align="center">44.0</td><td align="center"></td><td align="center">18131413</td><td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv/18131413/model_0039999_e76410.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv/18131413/metrics.json">metrics</a></td></tr><!-- ROW: TTA cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv --> <tr><td align="left">above + test-time aug.</td><td align="center"></td><td align="center"></td><td align="center">51.9</td><td align="center">45.9</td><td align="center"></td><td align="center"></td><td align="center"></td></tr></tbody></table>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556<img src=".github/Detectron2-Logo-Horz.svg" width="300" >
Detectron2 is Facebook AI Research's next generation software systemthat implements state-of-the-art object detection algorithms.It is a ground-up rewrite of the previous version,[Detectron](https://github.com/facebookresearch/Detectron/),and it originates from [maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark/).
<div align="center"> <img src="https://user-images.githubusercontent.com/1381301/66535560-d3422200-eace-11e9-9123-5535d469db19.png"/></div>
### What's New* It is powered by the [PyTorch](https://pytorch.org) deep learning framework.* Includes more features such as panoptic segmentation, densepose, Cascade R-CNN, rotated bounding boxes, etc.* Can be used as a library to support [different projects](projects/) on top of it. We'll open source more research projects in this way.* It [trains much faster](https://detectron2.readthedocs.io/notes/benchmarks.html).
See our [blog post](https://ai.facebook.com/blog/-detectron2-a-pytorch-based-modular-object-detection-library-/)to see more demos and learn about detectron2.
## Installation
See [INSTALL.md](INSTALL.md).
## Quick Start
See [GETTING_STARTED.md](GETTING_STARTED.md),or the [Colab Notebook](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5).
Learn more at our [documentation](https://detectron2.readthedocs.org).And see [projects/](projects/) for some projects that are built on top of detectron2.
## Model Zoo and Baselines
We provide a large set of baseline results and trained models available for download in the [Detectron2 Model Zoo](MODEL_ZOO.md).
## License
Detectron2 is released under the [Apache 2.0 license](LICENSE).
## Citing Detectron2
If you use Detectron2 in your research or wish to refer to the baseline results published in the [Model Zoo](MODEL_ZOO.md), please use the following BibTeX entry.
```BibTeX@misc{wu2019detectron2, author = {Yuxin Wu and Alexander Kirillov and Francisco Massa and Wan-Yen Lo and Ross Girshick}, title = {Detectron2}, howpublished = {\url{https://github.com/facebookresearch/detectron2}}, year = {2019}}```app.pyAdded+373
model/DensePose/__init__.pyAdded+158
model/DensePose/__pycache__/__init__.cpython-310.pycAdded
model/DensePose/__pycache__/__init__.cpython-312.pycAdded
model/DensePose/__pycache__/__init__.cpython-39.pycAdded
model/SCHP/LICENSEAdded+21
model/SCHP/README.mdAdded+129
model/SCHP/__init__.pyAdded+163
model/SCHP/__pycache__/__init__.cpython-310.pycAdded
model/SCHP/__pycache__/__init__.cpython-39.pycAdded
model/SCHP/datasets/__init__.pyAdded
model/SCHP/datasets/__pycache__/__init__.cpython-39.pycAdded
model/SCHP/datasets/__pycache__/simple_extractor_dataset.cpython-39.pycAdded
model/SCHP/datasets/datasets.pyAdded+205
model/SCHP/datasets/simple_extractor_dataset.pyAdded+92
model/SCHP/datasets/target_generation.pyAdded+40
model/SCHP/environment.yamlAdded+49
model/SCHP/evaluate.pyAdded+210
model/SCHP/file_list.txtAdded
model/SCHP/mhp_extension/.ipynb_checkpoints/demo-checkpoint.ipynbAdded
model/SCHP/mhp_extension/README.mdAdded+38
model/SCHP/mhp_extension/coco_style_annotation_creator/__pycache__/pycococreatortools.cpython-37.pycAdded
model/SCHP/mhp_extension/coco_style_annotation_creator/human_to_coco.pyAdded+166
model/SCHP/mhp_extension/coco_style_annotation_creator/pycococreatortools.pyAdded+114
model/SCHP/mhp_extension/coco_style_annotation_creator/test_human2coco_format.pyAdded+74
model/SCHP/mhp_extension/data/DemoDataset/global_pic/demo.jpgAdded

model/SCHP/mhp_extension/demo.ipynbAdded
model/SCHP/mhp_extension/demo/demo.jpgAdded

model/SCHP/mhp_extension/demo/demo_global_human_parsing.pngAdded

model/SCHP/mhp_extension/demo/demo_instance_human_mask.pngAdded

model/SCHP/mhp_extension/demo/demo_multiple_human_parsing.pngAdded

model/SCHP/mhp_extension/detectron2/.circleci/config.ymlAdded+179
model/SCHP/mhp_extension/detectron2/.clang-formatAdded+85
model/SCHP/mhp_extension/detectron2/.flake8Added+9
model/SCHP/mhp_extension/detectron2/.github/CODE_OF_CONDUCT.mdAdded+5
model/SCHP/mhp_extension/detectron2/.github/CONTRIBUTING.mdAdded+49
model/SCHP/mhp_extension/detectron2/.github/Detectron2-Logo-Horz.svgAdded
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE.mdAdded+5
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/bugs.mdAdded+36
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/config.ymlAdded+9
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/feature-request.mdAdded+31
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/questions-help-support.mdAdded+26
model/SCHP/mhp_extension/detectron2/.github/ISSUE_TEMPLATE/unexpected-problems-bugs.mdAdded+45
model/SCHP/mhp_extension/detectron2/.github/pull_request_template.mdAdded+9
model/SCHP/mhp_extension/detectron2/.gitignoreAdded+46
model/SCHP/mhp_extension/detectron2/GETTING_STARTED.mdAdded+79
model/SCHP/mhp_extension/detectron2/INSTALL.mdAdded+184
model/SCHP/mhp_extension/detectron2/LICENSEAdded+201
model/SCHP/mhp_extension/detectron2/MODEL_ZOO.mdAdded+903
model/SCHP/mhp_extension/detectron2/README.mdAdded+56