File size: 9,722 Bytes
97b92e8
 
 
 
 
 
 
 
 
 
 
 
 
f588760
97b92e8
 
 
 
 
f588760
97b92e8
 
f588760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b92e8
 
f588760
97b92e8
 
f588760
97b92e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f588760
97b92e8
 
 
 
 
 
 
 
53a6d4b
 
f588760
97b92e8
 
 
53a6d4b
97b92e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53a6d4b
97b92e8
 
 
 
 
 
 
 
f588760
 
 
 
 
 
 
97b92e8
 
 
 
 
 
 
 
 
 
 
f588760
 
 
97b92e8
 
 
 
 
 
f588760
97b92e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f588760
97b92e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f588760
53a6d4b
97b92e8
f588760
97b92e8
 
f588760
 
97b92e8
f588760
 
97b92e8
f588760
53a6d4b
97b92e8
 
f588760
97b92e8
 
 
 
f588760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# Copyright 2022 Daniel van Strien.
#
# 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, software
# distributed 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 and
# limitations under the License.
"""NLS Chapbook Illustrations"""

import collections
import json
import os
from typing import Any, Dict, List
import pandas as pd
import datasets

_CITATION = """@inproceedings{10.1145/3476887.3476893,
author = {Dutta, Abhishek and Bergel, Giles and Zisserman, Andrew},
title = {Visual Analysis of Chapbooks Printed in Scotland},
year = {2021},
isbn = {9781450386906},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3476887.3476893},
doi = {10.1145/3476887.3476893},
abstract = {Chapbooks were short, cheap printed booklets produced in large quantities in Scotland, England, Ireland, North America and much of Europe between roughly the seventeenth and nineteenth centuries. A form of popular literature containing songs, stories, poems, games, riddles, religious writings and other content designed to appeal to a wide readership, they were frequently illustrated, particularly on their title-pages. This paper describes the visual analysis of such chapbook illustrations. We automatically extract all the illustrations contained in the National Library of Scotland Chapbooks Printed in Scotland dataset, and create a visual search engine to search this dataset using full or part-illustrations as queries. We also cluster these illustrations based on their visual content, and provide keyword-based search of the metadata associated with each publication. The visual search; clustering of illustrations based on visual content; and metadata search features enable researchers to forensically analyse the chapbooks dataset and to discover unnoticed relationships between its elements. We release all annotations and software tools described in this paper to enable reproduction of the results presented and to allow extension of the methodology described to datasets of a similar nature.},
booktitle = {The 6th International Workshop on Historical Document Imaging and Processing},
pages = {67–72},
numpages = {6},
keywords = {illustration detection, chapbooks, image search, visual grouping, printing, digital scholarship, illustration dataset},
location = {Lausanne, Switzerland},
series = {HIP '21}
}
"""


_DESCRIPTION = "This dataset comprises of images from chapbooks held by the National Library of Scotland and digitised and published as its Chapbooks Printed in Scotland dataset"


_HOMEPAGE = "https://www.robots.ox.ac.uk/~vgg/research/chapbooks/"


_LICENSE = "Public Domain Mark 1.0"  # TODO confirm licence terms for annotations


_IMAGES_URL = "https://nlsfoundry.s3.amazonaws.com/data/nls-data-chapbooks.zip"

# TODO update url if this is merged upstream
_ANNOTATIONS_URL = "https://gitlab.com/davanstrien/nls-chapbooks-illustrations/-/raw/master/data/annotations/step5-manual-verification-image-0-47329_train_coco.json"


class NationalLibraryScotlandChapBooksConfig(datasets.BuilderConfig):
    """BuilderConfig for National Library of Scotland Chapbooks dataset."""

    def __init__(self, name, **kwargs):
        super(NationalLibraryScotlandChapBooksConfig, self).__init__(
            version=datasets.Version("1.0.0"),
            name=name,
            description="NLS Chapbook Illustrations",
            **kwargs,
        )


class NationalLibraryScotlandChapBooks(datasets.GeneratorBasedBuilder):
    """National Library of Scotland Chapbooks dataset."""

    BUILDER_CONFIGS = [
        NationalLibraryScotlandChapBooksConfig("illustration-detection"),
        NationalLibraryScotlandChapBooksConfig("image-classification"),
        NationalLibraryScotlandChapBooksConfig("image-matching"),
    ]

    def _info(self):
        if self.config.name == "illustration-detection":
            features = datasets.Features(
                {
                    "image_id": datasets.Value("int64"),
                    "image": datasets.Image(),
                    "width": datasets.Value("int32"),
                    "height": datasets.Value("int32"),
                }
            )
            object_dict = {
                "category_id": datasets.ClassLabel(
                    names=["early_printed_illustration"]
                ),
                "image_id": datasets.Value("string"),
                "id": datasets.Value("int64"),
                "area": datasets.Value("int64"),
                "bbox": datasets.Sequence(datasets.Value("float32"), length=4),
                "segmentation": [[datasets.Value("float32")]],
                "iscrowd": datasets.Value("bool"),
            }
            features["objects"] = [object_dict]
        if self.config.name == "image-classification":
            features = datasets.Features(
                {
                    "image": datasets.Image(),
                    "label": datasets.ClassLabel(
                        num_classes=2, names=["not-illustrated", "illustrated"]
                    ),
                }
            )
        if self.config.name == "image-matching":
            features = datasets.Features(
                {
                    "image": datasets.Image(),
                    "group-label": datasets.Value("int32"),
                }
            )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        images = dl_manager.download_and_extract(_IMAGES_URL)
        annotations = dl_manager.download(_ANNOTATIONS_URL)
        image_match_annotations = dl_manager.download(
            "illustration-group-specifications[83].csv"
        )
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "annotations_file": os.path.join(annotations),
                    "image_dir": os.path.join(images, "nls-data-chapbooks"),
                    "image_match_annotations": image_match_annotations,
                },
            )
        ]

    def _get_image_id_to_annotations_mapping(
        self, annotations: List[Dict]
    ) -> Dict[int, List[Dict[Any, Any]]]:
        """
        A helper function to build a mapping from image ids to annotations.
        """
        image_id_to_annotations = collections.defaultdict(list)
        for annotation in annotations:
            image_id_to_annotations[annotation["image_id"]].append(annotation)
        return image_id_to_annotations

    def _generate_examples(self, annotations_file, image_dir, image_match_annotations):
        def _image_info_to_example(image_info, image_dir):
            image = image_info["file_name"]
            return {
                "image_id": image_info["id"],
                "image": os.path.join(image_dir, image),
                "width": image_info["width"],
                "height": image_info["height"],
            }

        with open(annotations_file, encoding="utf8") as f:
            annotation_data = json.load(f)
            images = annotation_data["images"]
            annotations = annotation_data["annotations"]
            image_id_to_annotations = self._get_image_id_to_annotations_mapping(
                annotations
            )

            if self.config.name == "illustration-detection":
                for idx, image_info in enumerate(images):
                    example = _image_info_to_example(image_info, image_dir)
                    annotations = image_id_to_annotations[image_info["id"]]
                    objects = []
                    for annotation in annotations:
                        category_id = annotation["category_id"]
                        if category_id == 1:
                            annotation["category_id"] = 0
                        objects.append(annotation)
                    example["objects"] = objects
                    yield (idx, example)
            if self.config.name == "image-classification":
                for idx, image_info in enumerate(images):
                    annotations = image_id_to_annotations[image_info["id"]]
                    label = 0 if len(annotations) < 1 else 1
                    example = {
                        "image": os.path.join(image_dir, image_info["file_name"]),
                        "label": label,
                    }

                    yield (idx, example)
            if self.config.name == "image-matching":
                df = pd.read_csv(image_match_annotations, dtype={"file_id": "string"})
                df = df.drop_duplicates(subset=["filename"], keep=False)
                df = df.set_index("filename", drop=True)
                mapping = df.to_dict("index")
                for idx, image_info in enumerate(images):
                    filename = image_info["file_name"]
                    match = mapping.get(filename)
                    if match:
                        match = match["set_id"]
                    example = {
                        "image": os.path.join(image_dir, image_info["file_name"]),
                        "group-label": match,
                    }
                    yield (idx, example)