File size: 7,749 Bytes
85699d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c58c4fe
 
85699d6
 
c58c4fe
 
 
 
 
 
85699d6
 
 
 
 
 
c58c4fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85699d6
 
 
 
 
 
 
 
 
 
 
 
 
c58c4fe
 
85699d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c58c4fe
85699d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c58c4fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85699d6
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.

"""Dataset for filtered Kvasir-instrument and Hyper-Kvasir with bounding boxes."""

import os
import json
from PIL import Image
import datasets

import os
import json
import pandas as pd
import hashlib
from collections import defaultdict
import numpy as np


def cal_mid(bx): return [[[float(box['xmin'] + box['xmax']) / 2,
                           float(box['ymin'] + box['ymax']) / 2] for box in bx]]


def cal_mid_xy(bx): return [{"x": float(box['xmin'] + box['xmax']) / 2,
                             "y": float(box['ymin'] + box['ymax']) / 2} for box in bx]


def cal_sha256(file_path): return hashlib.sha256(
    open(file_path, 'rb').read()).hexdigest()


def convert_to_json_format(file_path, image_width, image_height):
    with open(file_path, 'r') as file:
        return [
            {
                "label": line.split()[0],
                "xmin": int((float(line.split()[1]) - float(line.split()[3]) / 2) * image_width),
                "ymin": int((float(line.split()[2]) - float(line.split()[4]) / 2) * image_height),
                "xmax": int((float(line.split()[1]) + float(line.split()[3]) / 2) * image_width),
                "ymax": int((float(line.split()[2]) + float(line.split()[4]) / 2) * image_height),
            }
            for line in file.readlines()
        ]


class_map = {"0": "normal",  "1": "cluster", "2": "pinhead"}

hyper_label_img_path = '/global/D1/projects/HOST/Datasets/hyper-kvasir/labeled-images/image-labels.csv'

hyper_df = pd.read_csv(hyper_label_img_path)

hyper_seg_img_path = '/global/D1/projects/HOST/Datasets/hyper-kvasir/segmented-images/bounding-boxes.json'
hyper_seg_img_base_path = "/global/D1/projects/HOST/Datasets/hyper-kvasir/segmented-images/images"

instr_seg_img_path = '/global/D1/projects/HOST/Datasets/kvasir-instrument/bboxes.json'
instr_seg_img_base_path = '/global/D1/projects/HOST/Datasets/kvasir-instrument/images/'

hyper_seg_imgs = json.load(open(hyper_seg_img_path))
instr_seg_imgs = json.load(open(instr_seg_img_path))

visem_root = "/global/D1/projects/HOST/Datasets/visem-tracking"

_CITATION = """\
@article{kvasir,
    title={Kvasir-instrument and Hyper-Kvasir datasets for bounding box annotations},
    author={Sushant Gautam and collaborators},
    year={2024}
}
"""

_DESCRIPTION = """
Filtered Kvasir-instrument and Hyper-Kvasir datasets with bounding boxes for medical imaging tasks. 
Each entry contains images, bounding box coordinates, and additional metadata.
"""

_HOMEPAGE = "https://example.com/kvasir-hyper-bbox"

_LICENSE = "CC BY-NC 4.0"

_URLS = {
    "filtered_data": "https://example.com/kvasir-hyper-bbox-dataset.zip"
}


class KvasirHyperBBox(datasets.GeneratorBasedBuilder):
    """Dataset for Kvasir-instrument and Hyper-Kvasir with bounding boxes."""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="bbox_dataset",
            version=VERSION,
            description="Dataset with bounding box annotations."
        )
    ]

    DEFAULT_CONFIG_NAME = "bbox_dataset"

    def _info(self):
        features = datasets.Features({
            "image_data": datasets.Image(),
            "image_sha256": datasets.Value("string"),
            "points": datasets.Sequence(datasets.Sequence(datasets.Sequence(datasets.Value("float32")))),
            "count": datasets.Value("int64"),
            "label": datasets.Value("string"),
            "collection_method": datasets.Value("string"),
            "classification": datasets.Value("string"),
            "organ": datasets.Value("string")
        })

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
            features=features
        )

    def _split_generators(self, dl_manager):
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={},
            )
        ]

    def _generate_examples(self):
        for key, entry in hyper_seg_imgs.items():
            img_path = os.path.join(hyper_seg_img_base_path, f"{key}.jpg")
            hyper_entry = hyper_df.loc[hyper_df['Video file'] == key].iloc[0]
            yield key, {
                "image_data": open(img_path, 'rb').read(),
                "image_sha256": cal_sha256(img_path),
                "points":  cal_mid(entry['bbox']),
                "count": len(entry['bbox']),
                "label": hyper_entry.Finding,
                "collection_method": 'counting',
                "classification": hyper_entry.Classification,
                "organ": hyper_entry.Organ
            }

        for key, entry in instr_seg_imgs.items():
            img_path = os.path.join(instr_seg_img_base_path, f"{key}.jpg")
            yield key, {
                "image_data": open(img_path, 'rb').read(),
                "image_sha256": cal_sha256(img_path),
                "points":  cal_mid(entry['bbox']),
                "count": len(entry['bbox']),
                "label": "instrument",
                "collection_method": "counting",
                "classification": "instrument",
                "organ": "instrument"
            }

        for folder in os.listdir(visem_root):
            folder_path = os.path.join(visem_root, folder)
            labels_all = os.listdir(folder_path+"/labels")
            images = os.listdir(folder_path+"/images")
            height, width = Image.open(os.path.join(
                folder_path, "images", images[0])).size
            labels = [labels_all[i] for i in np.linspace(
                0, len(labels_all)-1, 250).astype(int)]
            for label in labels:
                label_path = os.path.join(folder_path, "labels", label)
                image_path = label_path.replace(
                    "/labels/", "/images/").replace(".txt", ".jpg")
                entry_bbox = convert_to_json_format(label_path, width, height)
                label_dict = defaultdict(list)
                for entry in entry_bbox:
                    label_dict[entry['label']].append(entry)
                for label in label_dict:
                    yield cal_sha256(image_path)+label, {
                        "image_data": open(image_path, 'rb').read(),
                        "image_sha256": cal_sha256(image_path),
                        "points": cal_mid(label_dict[label]),
                        "count": len(label_dict[label]),
                        "label": class_map[label],
                        "collection_method": "counting",
                        "classification": "sperm",
                        "organ": "visem dataset"
                    }


# rm -rf /home/sushant/.cache/huggingface/modules/datasets_modules/datasets/kvasir-points_datasets_script/ /home/sushant/.cache/huggingface/datasets/kvasir-points_datasets_script 
# datasets-cli test  /global/D1/projects/HOST/Datasets/hyper-kvasir/sushant-experiments/kvasir-points_datasets_script.py --save_info  --all_configs --trust_remote_cod
# huggingface-cli upload kvasir-points . . --repo-type dataset