pascal_voc / pascal_voc.py
fuliucansheng's picture
add new file
411cb45
import os
import logging
import datasets
import xml.etree.ElementTree as ET
from PIL import Image
from collections import defaultdict
_CITATION = """
PASCAL_VOC
"""
_DESCRIPTION = """
PASCAL_VOC
"""
_URLS = {
"voc2007": "voc2007.tar.gz",
"voc2012": "voc2012.tar.gz",
}
# fmt: off
CLASS_INFOS = [
# class name id train color
( 'aeroplane' , 0 , 0 , ( 128, 0, 0) ),
( 'bicycle' , 1 , 1 , ( 0, 128, 0) ),
( 'bird' , 2 , 2 , ( 128, 128, 0) ),
( 'boat' , 3 , 3 , ( 0, 0, 128) ),
( 'bottle' , 4 , 4 , ( 128, 0, 128) ),
( 'bus' , 5 , 5 , ( 0, 128, 128) ),
( 'car' , 6 , 6 , ( 128, 128, 128) ),
( 'cat' , 7 , 7 , ( 64, 0, 0) ),
( 'chair' , 8 , 8 , ( 192, 0, 0) ),
( 'cow' , 9 , 9 , ( 64, 128, 0) ),
( 'diningtable' , 10 , 10 , ( 192, 128, 0) ),
( 'dog' , 11 , 11 , ( 64, 0, 128) ),
( 'horse' , 12 , 12 , ( 192, 0, 128) ),
( 'motorbike' , 13 , 13 , ( 64, 128, 128) ),
( 'person' , 14 , 14 , ( 192, 128, 128) ),
( 'pottedplant' , 15 , 15 , ( 0, 64, 0) ),
( 'sheep' , 16 , 16 , ( 128, 64, 0) ),
( 'sofa' , 17 , 17 , ( 0, 192, 0) ),
( 'train' , 18 , 18 , ( 128, 192, 0) ),
( 'tvmonitor' , 19 , 19 , ( 0, 64, 128) ),
( 'background' , 20 , 20 , ( 0, 0, 0) ),
( 'borderingregion' , 255, 21 , ( 224, 224, 192) ),
]
ACTION_INFOS = [
# class name id
( 'phoning' , 0 ),
( 'playinginstrument' , 1 ),
( 'reading' , 2 ),
( 'ridingbike' , 3 ),
( 'ridinghorse' , 4 ),
( 'running' , 5 ),
( 'takingphoto' , 6 ),
( 'usingcomputer' , 7 ),
( 'walking' , 8 ),
( 'jumping' , 9 ),
( 'other' , 10 ),
]
LAYOUT_INFOS = [
# class name id
( 'Frontal' , 0 ),
( 'Left' , 1 ),
( 'Rear' , 2 ),
( 'Right' , 3 ),
( 'Unspecified' , 4 ),
]
# fmt: on
CLASS_NAMES = [CLASS_INFO[0] for CLASS_INFO in CLASS_INFOS]
ACTION_NAMES = [ACTION_INFO[0] for ACTION_INFO in ACTION_INFOS]
LAYOUT_NAMES = [LAYOUT_INFO[0] for LAYOUT_INFO in LAYOUT_INFOS]
CLASS_DICT = {CLASS_INFO[0]: CLASS_INFO[2] for CLASS_INFO in CLASS_INFOS}
ACTION_DICT = {ACTION_INFO[0]: ACTION_INFO[1] for ACTION_INFO in ACTION_INFOS}
LAYOUT_DICT = {LAYOUT_INFO[0]: LAYOUT_INFO[1] for LAYOUT_INFO in LAYOUT_INFOS}
# datasets.Features
action_features = datasets.Features(
{
"id": datasets.Value("int32"),
"image": datasets.features.Image(),
"height": datasets.Value("int32"),
"width": datasets.Value("int32"),
"classes": datasets.features.Sequence(datasets.Value("int32")),
"objects": datasets.features.Sequence(
{
"bboxes": datasets.Sequence(datasets.Value("float32")),
"classes": datasets.features.ClassLabel(names=ACTION_NAMES),
"difficult": datasets.Value("int32"),
}
),
}
)
layout_features = datasets.Features(
{
"id": datasets.Value("int32"),
"image": datasets.features.Image(),
"height": datasets.Value("int32"),
"width": datasets.Value("int32"),
"classes": datasets.features.Sequence(datasets.Value("int32")),
"objects": datasets.features.Sequence(
{
"bboxes": datasets.Sequence(datasets.Value("float32")),
"classes": datasets.features.ClassLabel(names=LAYOUT_NAMES),
"difficult": datasets.Value("int32"),
}
),
}
)
main_features = datasets.Features(
{
"id": datasets.Value("int32"),
"image": datasets.features.Image(),
"height": datasets.Value("int32"),
"width": datasets.Value("int32"),
"classes": datasets.features.Sequence(datasets.Value("int32")),
"objects": datasets.features.Sequence(
{
"bboxes": datasets.Sequence(datasets.Value("float32")),
"classes": datasets.features.ClassLabel(names=CLASS_NAMES),
"difficult": datasets.Value("int32"),
}
),
}
)
segmentation_features = datasets.Features(
{
"id": datasets.Value("int32"),
"image": datasets.features.Image(),
"height": datasets.Value("int32"),
"width": datasets.Value("int32"),
"classes": datasets.features.Sequence(datasets.Value("int32")),
"class_gt_image": datasets.features.Image(),
"object_gt_image": datasets.features.Image(),
}
)
_DATASET_FEATURES = {
"action": action_features,
"layout": layout_features,
"main": main_features,
"segmentation": segmentation_features,
}
def get_main_classes(data_folder):
class_infos = defaultdict(set)
class_folder = os.path.join(data_folder, "ImageSets", "Main")
for f in os.listdir(class_folder):
if not f.endswith(".txt") or len(f.split("_")) != 2:
continue
lines = open(os.path.join(class_folder, f), "r").read().split("\n")
name = f.split("_")[0]
for line in lines:
spans = line.strip().split(" ")
spans = list(filter(lambda x: x.strip() != "", spans))
if len(spans) != 2 or int(spans[1]) != 1:
continue
class_infos[spans[0]].add(name)
return class_infos
def get_annotation(data_folder):
anno_infos = dict()
anno_folder = os.path.join(data_folder, "Annotations")
for f in os.listdir(anno_folder):
if not f.endswith(".xml"):
continue
anno_file = os.path.join(anno_folder, f)
anno_tree = ET.parse(anno_file)
objects = []
for obj in anno_tree.findall("./object"):
info = {
"class": obj.findall("./name")[0].text,
"bbox": [
int(float(obj.findall("./bndbox/xmin")[0].text)),
int(float(obj.findall("./bndbox/ymin")[0].text)),
int(float(obj.findall("./bndbox/xmax")[0].text)),
int(float(obj.findall("./bndbox/ymax")[0].text)),
],
}
if obj.findall("./pose"):
info["pose"] = obj.findall("./pose")[0].text
if obj.findall("./truncated"):
info["truncated"] = int(obj.findall("./truncated")[0].text)
if obj.findall("./difficult"):
info["difficult"] = int(obj.findall("./difficult")[0].text)
else:
info["difficult"] = 0
if obj.findall("./occluded"):
info["occluded"] = int(obj.findall("./occluded")[0].text)
if obj.findall("./actions"):
info["action"] = [
action.tag
for action in obj.findall("./actions/")
if int(action.text) == 1
][0]
objects.append(info)
anno_info = {
"image": anno_tree.findall("./filename")[0].text,
"height": int(anno_tree.findall("./size/height")[0].text),
"width": int(anno_tree.findall("./size/width")[0].text),
"segmented": int(anno_tree.findall("./segmented")[0].text),
"objects": objects,
}
stem, suffix = os.path.splitext(f)
anno_infos[stem] = anno_info
return anno_infos
class PASCALConfig(datasets.BuilderConfig):
def __init__(self, data_name, task_name, **kwargs):
"""
Args:
**kwargs: keyword arguments forwarded to super.
"""
super().__init__(**kwargs)
assert data_name in ["voc2007", "voc2012"] and task_name in [
"action",
"layout",
"main",
"segmentation",
]
assert not (data_name == "voc2007" and task_name == "action")
self.data_name = data_name
self.task_name = task_name
class PASCALDataset(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
PASCALConfig(
name="voc2007_layout",
version=datasets.Version("1.0.0", ""),
description="voc2007 layout dataset",
data_name="voc2007",
task_name="layout",
),
PASCALConfig(
name="voc2007_main",
version=datasets.Version("1.0.0", ""),
description="voc2007 main dataset",
data_name="voc2007",
task_name="main",
),
PASCALConfig(
name="voc2007_segmentation",
version=datasets.Version("1.0.0", ""),
description="voc2007 segmentation dataset",
data_name="voc2007",
task_name="segmentation",
),
PASCALConfig(
name="voc2012_action",
version=datasets.Version("1.0.0", ""),
description="voc2012 action dataset",
data_name="voc2012",
task_name="action",
),
PASCALConfig(
name="voc2012_layout",
version=datasets.Version("1.0.0", ""),
description="voc2012 layout dataset",
data_name="voc2012",
task_name="layout",
),
PASCALConfig(
name="voc2012_main",
version=datasets.Version("1.0.0", ""),
description="voc2012 main dataset",
data_name="voc2012",
task_name="main",
),
PASCALConfig(
name="voc2012_segmentation",
version=datasets.Version("1.0.0", ""),
description="voc2012 segmentation dataset",
data_name="voc2012",
task_name="segmentation",
),
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=_DATASET_FEATURES[self.config.task_name],
# No default supervised_keys (as we have to pass both question
# and context as input).
supervised_keys=None,
homepage="https://fuliucansheng.github.io/",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
downloaded_files = dl_manager.download_and_extract(_URLS[self.config.data_name])
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepath": downloaded_files, "split": "train"},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": downloaded_files, "split": "val"},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"filepath": downloaded_files, "split": "test"},
),
]
def _generate_examples(self, filepath, split):
"""This function returns the examples in the raw (text) form."""
logging.info("generating examples from = %s, split = %s", filepath, split)
data_folder = os.path.join(filepath, os.listdir(filepath)[0])
anno_infos = get_annotation(data_folder)
class_infos = get_main_classes(data_folder)
data_file = os.path.join(
data_folder, "ImageSets", self.config.task_name.capitalize(), f"{split}.txt"
)
with open(data_file, encoding="utf-8") as f:
for id_, line in enumerate(f):
line = line.strip()
if line.count(" ") > 0:
line = line.split(" ")[0]
anno_info = anno_infos.get(line)
if anno_info is None:
continue
image = os.path.join(data_folder, "JPEGImages", anno_info["image"])
if not os.path.exists(image):
continue
classes = (
[CLASS_DICT[c] for c in class_infos.get(line.strip())]
if line.strip() in class_infos
else []
)
example = {
"id": id_,
"image": Image.open(os.path.abspath(image)),
"height": anno_info["height"],
"width": anno_info["width"],
"classes": classes,
}
objects_info = anno_info["objects"]
if self.config.task_name == "action":
example["objects"] = [
{
"bboxes": object_info["bbox"],
"classes": object_info["action"],
"difficult": object_info["difficult"],
}
for object_info in objects_info
if "action" in object_info
]
if len(example["objects"]) == 0 and split != "test":
continue
if self.config.task_name == "layout":
example["objects"] = [
{"bboxes": object_info["bbox"], "classes": object_info["pose"], "difficult": object_info["difficult"],}
for object_info in objects_info
if "pose" in object_info
]
if len(example["objects"]) == 0 and split != "test":
continue
if self.config.task_name == "main":
example["objects"] = [
{"bboxes": object_info["bbox"], "classes": object_info["class"], "difficult": object_info["difficult"],}
for object_info in objects_info
if "class" in object_info
]
if len(example["objects"]) == 0 and split != "test":
continue
if self.config.task_name == "segmentation":
example["class_gt_image"] = Image.open(os.path.abspath(
os.path.join(
data_folder,
"SegmentationClass",
anno_info["image"].replace(".jpg", ".png"),
)
))
example["object_gt_image"] = Image.open(os.path.abspath(
os.path.join(
data_folder,
"SegmentationObject",
anno_info["image"].replace(".jpg", ".png"),
)
))
yield id_, example