# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors. # # 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. # Lint as: python3 """GTSRB: German Traffic Sign Recognition Benchmark.""" import csv import datasets from datasets import Dataset, DatasetDict import os from datasets.tasks import ImageClassification logger = datasets.logging.get_logger(__name__) # df_train = pd.read_csv('Test.csv') # df_test = pd.read_csv('Train.csv') # train = Dataset.from_pandas(df_train) # test = Dataset.from_pandas(df_test) # dataset = DatasetDict() # dataset['train'] = train # dataset['test'] = test _CITATION = """\ @article { Stallkamp2012, title = "Man vs. computer: Benchmarking machine learning algorithms for traffic sign recognition", journal = "Neural Networks", volume = "", number = "0", pages = " - ", year = "2012", note = "", issn = "0893-6080", doi = "10.1016/j.neunet.2012.02.016", url = "http://www.sciencedirect.com/science/article/pii/S0893608012000457", author = "J. Stallkamp and M. Schlipsing and J. Salmen and C. Igel", keywords = "Traffic sign recognition", keywords = "Machine learning", keywords = "Convolutional neural networks", keywords = "Benchmarking" } """ _DESCRIPTION = """\ Recognition of traffic signs is a challenging real-world problem of high industrial relevance. Although commercial systems have reached the market and several studies on this topic have been published, systematic unbiased comparisons of different approaches are missing and comprehensive benchmark datasets are not freely available. \ Traffic sign recognition is a multi-class classification problem with unbalanced class frequencies. Traffic signs can provide a wide range of variations between classes in terms of color, shape, and the presence of pictograms or text. However, there exist subsets of classes (e. g., speed limit signs) that are very similar to each other. \ The classifier has to cope with large variations in visual appearances due to illumination changes, partial occlusions, rotations, weather conditions, etc. \ Humans are capable of recognizing the large variety of existing road signs with close to 100% correctness. This does not only apply to real-world driving, which provides both context and multiple views of a single traffic sign, but also to the recognition from single images. """ _FEATURES = datasets.Features({ "Width": datasets.Value("uint16"), "Height": datasets.Value("uint8"), "Roi.X1": datasets.Value("uint8"), "Roi.Y1": datasets.Value("uint8"), "Roi.X2": datasets.Value("uint8"), "Roi.Y2": datasets.Value("uint8"), "ClassId": datasets.ClassLabel(num_classes=43), "Path": datasets.Image("png"), # "Path": datasets.Value("string"), }) _IMAGES_DIR = "GTSRB/Images" _URL = "https://github.com/bazylhorsey/gtsrb/archive/refs/tags/0.0.0.tar.gz" # importing the "tarfile" module # open file # file = tarfile.open("https://github.com/bazylhorsey/gtsrb/archive/refs/tags/0.0.0.tar.gz") # file.extractall('temp') class GTSRBConfig(datasets.BuilderConfig): """BuilderConfig for GTSRB.""" def __init__(self, **kwargs): """BuilderConfig for GTSRB. Args: **kwargs: keyword arguments forwarded to super. """ super(GTSRBConfig, self).__init__(**kwargs) class GTSRB(datasets.GeneratorBasedBuilder): """GTSRB: German Traffic Sign Recognition Benchmark.""" BUILDER_CONFIGS = [ GTSRBConfig( name="gtsrb", version=datasets.Version("0.0.0", ""), description="GTSRB: German Traffic Sign Recognition Benchmark.", ), ] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=_FEATURES, # No default supervised_keys (as we have to pass both question # and context as input). supervised_keys=["ClassId"], homepage="https://benchmark.ini.rub.de/gtsrb_news.html", citation=_CITATION, license="gnu public license", task_templates=[ImageClassification(image_column="Path", label_column="ClassId")], ) def _split_generators(self, dl_manager): archive_path = dl_manager.download(_URL) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": "Train.csv", "images": dl_manager.startswith("GTSRB/Train/").iter_archive(archive_path), }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "filepath": "Test.csv", "images": dl_manager.startswith("GTSRB/Test/").iter_archive(archive_path), } ), ] def _generate_examples(self, images, filepath): """This function returns the examples in the raw (text) form.""" # logger.info("generating examples from = %s", filepath) # key = 0 # with open(filepath, encoding="utf-8") as f: # GTSRB = csv.reader(f) # for article in GTSRB["data"]: # title = article.get("title", "") # for paragraph in article["paragraphs"]: # context = paragraph["context"] # do not strip leading blank spaces GH-2585 # for qa in paragraph["qas"]: # answer_starts = [answer["answer_start"] for answer in qa["answers"]] # answers = [answer["text"] for answer in qa["answers"]] # # Features currently used are "context", "question", and "answers". # # Others are extracted here for the ease of future expansions. # yield key, { # "title": title, # "context": context, # "question": qa["question"], # "id": qa["id"], # "answers": { # "answer_start": answer_starts, # "text": answers, # }, # } # key += 1 # with open(filepath, encoding="utf-8") as f: # reader = csv.reader(f) # for id_, row in enumerate(reader): # if id_ == 0: # continue # yield id_, { # "Width": int(row[0]), # "Height": int(row[1]), # "Roi.X1": int(row[2]), # "Roi.Y1": int(row[3]), # "Roi.X2": int(row[4]), # "Roi.Y2": int(row[5]), # "ClassId": int(row[6]), # "Path": str(row[7]), # } with open(filepath, encoding="utf-8") as f: files_to_keep = set(f.read().split("\n")) for file_path, file_obj in images: print(file_path, file_obj) if file_path.startswith(_IMAGES_DIR): if file_path[len(_IMAGES_DIR) : -len(".jpg")] in files_to_keep: label = file_path.split("/")[2] yield file_path, { "image": {"path": file_path, "bytes": file_obj.read()}, "label": label, }