├── .gitignore ├── LICENSE ├── README.md ├── common ├── __init__.py └── load_records.py ├── meta ├── frequency_12k.json ├── imagenet_12k_labels.txt └── imagenet_22k_labels.txt ├── misc ├── missing.py ├── process.py └── resize.py ├── tfds ├── __init__.py ├── helpers │ └── __init__.py ├── imagenet12k.py ├── imagenet22k.py ├── imagenet22k_test.py ├── imagenet_12k_labels.txt └── imagenet_22k_labels.txt └── wds ├── build_wds.py └── tfds_to_wds.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # PyCharm 101 | .idea 102 | 103 | output/ 104 | 105 | # PyTorch weights 106 | *.tar 107 | *.pth 108 | *.pt 109 | *.torch 110 | *.gz 111 | Untitled.ipynb 112 | Testing notebook.ipynb 113 | 114 | # Root dir exclusions 115 | /*.csv 116 | /*.yaml 117 | /*.json 118 | /*.jpg 119 | /*.png 120 | /*.zip 121 | /*.tar.* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 Ross Wightman 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ImageNet-12k processing and split info 2 | 3 | This is some very hacky code and metadata for the ImageNet-12k splits used for training the 12k models in [`timm`](https://github.com/huggingface/pytorch-image-models) 4 | 5 | This ImageNet subset is based on the original `fall11_whole.tar` and is not compatible with the newer Winter 2021 release of ImageNet. 6 | 7 | ## Code 8 | Included: 9 | * TFDS helpers (in `tfds/`) to build 12k train + val or 22k (w/ 12k alternate annotation) and 12k val 10 | * Webdataset (in `wds/`) to build webdataset tars from scratch or convert from tfds for same shuffle 11 | * Misc scripts used to clean/analyze the original images in `misc/` 12 | 13 | *NOTE:* This code is not being maintained and is 'as is', it requires modifications to work in different environments. 14 | 15 | ## Metadata 16 | * `meta/train_12k.csv` the list of samples in 12k train split 17 | * `meta/train_full.csv` the list of samples in full 22k train split (but w/ held out val samples) 18 | * `meta/val_12k.csv` the list of samples in 12k validation split 19 | 20 | The validation set is the same for both and only covers the 12k subset. The 12k (11821) synsets were chosen based on being able to have 40 samples per synset for validation w/ at least 400 samples remaining for train. See `meta/frequency.json` for per-synset sample counts. 21 | 22 | Metadata .csv files are in a release asset and on HF datasets due to their size, see: 23 | * https://github.com/rwightman/imagenet-12k/releases/download/v1.0.0/meta.tar.gz 24 | * https://huggingface.co/datasets/rwightman/imagenet-12k-metadata 25 | -------------------------------------------------------------------------------- /common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwightman/imagenet-12k/c13cd81f275654d0a6cd565b0f739eb7f2401bc6/common/__init__.py -------------------------------------------------------------------------------- /common/load_records.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import re 4 | import operator 5 | from itertools import chain 6 | 7 | import numpy as np 8 | import pandas as pd 9 | 10 | MIN_DIM = 56 11 | 12 | IMG_EXTENSIONS = ['.png', '.jpg', '.jpeg'] 13 | 14 | 15 | def natural_key(string_): 16 | """See http://www.codinghorror.com/blog/archives/001018.html""" 17 | return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] 18 | 19 | 20 | def find_images(folder, types=IMG_EXTENSIONS): 21 | filenames = [] 22 | for root, subdirs, files in os.walk(folder, topdown=False): 23 | rel_path = os.path.relpath(root, folder) if (root != folder) else '' 24 | for f in files: 25 | base, ext = os.path.splitext(f) 26 | if ext.lower() in types: 27 | filenames.append(os.path.join(root, f)) 28 | 29 | filenames = list(sorted(filenames)) 30 | return filenames 31 | 32 | 33 | def distribute(sequence): 34 | """ 35 | Enumerate the sequence evenly over the interval (0, 1). 36 | 37 | >>> list(distribute('abc')) 38 | [(0.25, 'a'), (0.5, 'b'), (0.75, 'c')] 39 | """ 40 | m = len(sequence) + 1 41 | for i, x in enumerate(sequence, 1): 42 | yield i/m, x 43 | 44 | 45 | def intersperse(*sequences): 46 | """ 47 | Evenly intersperse the sequences. 48 | 49 | Based on https://stackoverflow.com/a/19293603/4518341 50 | 51 | >>> list(intersperse(range(10), 'abc')) 52 | [0, 1, 'a', 2, 3, 4, 'b', 5, 6, 7, 'c', 8, 9] 53 | >>> list(intersperse('XY', range(10), 'abc')) 54 | [0, 1, 'a', 2, 'X', 3, 4, 'b', 5, 6, 'Y', 7, 'c', 8, 9] 55 | >>> ''.join(intersperse('hlwl', 'eood', 'l r!')) 56 | 'hello world!' 57 | """ 58 | distributions = map(distribute, sequences) 59 | get0 = operator.itemgetter(0) 60 | for _, x in sorted(chain(*distributions), key=get0): 61 | yield x 62 | 63 | 64 | def load_records( 65 | train_csv, 66 | validation_csv, 67 | label_file, 68 | alt_label_name='', 69 | alt_label_file='', 70 | min_img_size=MIN_DIM, 71 | ): 72 | train_record_df = pd.read_csv(train_csv, index_col=None) 73 | train_record_df = train_record_df[ 74 | ~((train_record_df.height < min_img_size) | (train_record_df.width < min_img_size))] 75 | 76 | val_record_df = pd.read_csv(validation_csv, index_col=None) 77 | val_record_df = val_record_df[ 78 | ~((val_record_df.height < min_img_size) | (val_record_df.width < min_img_size))] 79 | 80 | if label_file and os.path.exists(label_file): 81 | print(f'loading {label_file}') 82 | with open(label_file, 'r') as sf: 83 | class_to_idx = {s.strip(): i for i, s in enumerate(sf.readlines())} 84 | else: 85 | class_to_idx = sorted(train_record_df['cls'].unique(), key=natural_key) 86 | class_to_idx = {k: i for i, k in enumerate(class_to_idx)} 87 | with open(label_file, 'w') as sf: 88 | sf.writelines(c + '\n' for c in class_to_idx.keys()) 89 | print('class to idx', len(class_to_idx)) 90 | 91 | train_record_df['label'] = train_record_df['cls'].map(class_to_idx).astype(int) 92 | val_record_df['label'] = val_record_df['cls'].map(class_to_idx).astype(int) 93 | 94 | if alt_label_file: 95 | assert alt_label_name 96 | with open(alt_label_file, 'r') as sf: 97 | print(f'loading {alt_label_file}') 98 | class_to_idx_alt = {s.strip(): i for i, s in enumerate(sf.readlines())} 99 | print('alt class to idx', len(class_to_idx_alt)) 100 | 101 | train_record_df[alt_label_name] = train_record_df['cls'].map(class_to_idx_alt).fillna(-1).astype(int) 102 | train_record_df = train_record_df[['filename', 'label', alt_label_name, 'cls']] 103 | val_record_df[alt_label_name] = val_record_df['cls'].map(class_to_idx_alt).fillna(-1).astype(int) 104 | val_record_df = val_record_df[['filename', 'label', alt_label_name, 'cls']] 105 | 106 | # intersperse alt label samples with others more evenly 107 | np.random.seed(42) 108 | record_df_alt = train_record_df[train_record_df.cls.isin(class_to_idx_alt)].index.to_numpy() 109 | record_df_rest = train_record_df[~train_record_df.cls.isin(class_to_idx_alt)].index.to_numpy() 110 | np.random.shuffle(record_df_alt) 111 | np.random.shuffle(record_df_rest) 112 | mixed = intersperse(record_df_alt, record_df_rest) 113 | train_record_df = train_record_df.loc[mixed] 114 | else: 115 | train_record_df = train_record_df[['filename', 'label', 'cls']] 116 | val_record_df = train_record_df[['filename', 'label', 'cls']] 117 | train_record_df = train_record_df.sample(frac=1, random_state=42) 118 | 119 | val_record_df = val_record_df.sample(frac=1, random_state=42) 120 | print('num train records:', len(train_record_df.index)) 121 | print('num val records:', len(val_record_df.index)) 122 | time.sleep(5) 123 | 124 | train_records = train_record_df.to_records(index=False) 125 | val_records = val_record_df.to_records(index=False) 126 | return train_records, val_records 127 | -------------------------------------------------------------------------------- /misc/missing.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import re 4 | #import cv2 5 | import shutil 6 | from collections import Counter 7 | from functools import partial 8 | from PIL import Image 9 | from PIL.ImageStat import Stat 10 | import numpy as np 11 | import pandas as pd 12 | import multiprocessing 13 | from collections import OrderedDict 14 | 15 | 16 | BASE_DIR = '/data/in21k_resized/' 17 | EXCLUDE_DIR = '/data/in21k_excluded/' 18 | VAL_DIR = os.path.join(BASE_DIR, 'validation') 19 | TRAIN_DIR = os.path.join(BASE_DIR, 'train') 20 | 21 | os.makedirs(EXCLUDE_DIR, exist_ok=True) 22 | 23 | val_set = pd.read_csv('meta/val_12k.csv') 24 | 25 | valid_classes = set(val_set.cls) 26 | 27 | #for f in glob.glob(BASE_DIR + '*'): 28 | # basename = os.path.basename(f) 29 | # if os.path.basename(f) not in valid_classes: 30 | # shutil.move(f, EXCLUDE_DIR) 31 | 32 | missing = 0 33 | for c, f in zip(val_set.cls, val_set.filename): 34 | src = os.path.join(BASE_DIR, c, f) 35 | if os.path.exists(src): 36 | dst_dir = os.path.join(VAL_DIR, c) 37 | dst_file = os.path.join(dst_dir, f) 38 | os.makedirs(dst_dir, exist_ok=True) 39 | shutil.move(src, dst_file) 40 | else: 41 | missing += 1 42 | 43 | print('missing', missing) 44 | 45 | os.makedirs(TRAIN_DIR, exist_ok=True) 46 | for c in valid_classes: 47 | src = os.path.join(BASE_DIR, c) 48 | if os.path.exists(src): 49 | shutil.move(os.path.join(BASE_DIR, c), os.path.join(TRAIN_DIR, c)) 50 | -------------------------------------------------------------------------------- /misc/process.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import shutil 4 | from collections import Counter 5 | from functools import partial 6 | from PIL import Image 7 | from PIL.ImageStat import Stat 8 | import numpy as np 9 | import pandas as pd 10 | import multiprocessing 11 | from collections import OrderedDict 12 | 13 | IMG_EXTENSIONS = ['.png', '.jpg', '.jpeg'] 14 | 15 | 16 | def natural_key(string_): 17 | """See http://www.codinghorror.com/blog/archives/001018.html""" 18 | return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] 19 | 20 | 21 | def find_images(folder, types=IMG_EXTENSIONS): 22 | filenames = [] 23 | for root, subdirs, files in os.walk(folder, topdown=False): 24 | rel_path = os.path.relpath(root, folder) if (root != folder) else '' 25 | for f in files: 26 | base, ext = os.path.splitext(f) 27 | if ext.lower() in types: 28 | filenames.append(os.path.join(root, f)) 29 | 30 | filenames = list(sorted(filenames)) 31 | return filenames 32 | 33 | 34 | def img_info(f): 35 | img = Image.open(f) 36 | fmt = img.format 37 | img = img.convert('RGB') 38 | s = Stat(img) 39 | mean = s.mean 40 | std = [x ** 0.5 for x in s.var] 41 | 42 | return img, (img.size, mean, std, fmt) 43 | 44 | 45 | def process_imgs(filnames, base_dir): 46 | cls_list = [] 47 | id_list = [] 48 | size_list = [] 49 | mean_list = [] 50 | std_list = [] 51 | format_list = [] 52 | error_list = [] 53 | for f in filnames: 54 | id_only = os.path.splitext(os.path.basename(f))[0] 55 | img_cls, img_id = id_only.split('_') 56 | try: 57 | img = Image.open(f) 58 | fmt = img.format 59 | 60 | mode_changed = False 61 | if img.mode not in ("RGB", "L"): 62 | print('Mode', img.mode) 63 | mode_changed = True 64 | img = img.convert('RGB') 65 | 66 | resized = False 67 | if max(img.size) > 896: 68 | w, h = img.size 69 | if w > h: 70 | ratio = h / w 71 | wn = 896 72 | hn = int(wn * ratio) 73 | else: 74 | ratio = w / h 75 | hn = 896 76 | wn = int(hn * ratio) 77 | print(f'resizing {w}, {h} to {wn}, {hn} ') 78 | img = img.resize((wn, hn), Image.BICUBIC, reducing_gap=3) 79 | resized = True 80 | 81 | if min(img.size) < 56: 82 | dest = os.path.relpath(f, base_dir) 83 | dest = os.path.join(base_dir, 'discard', dest) 84 | #os.makedirs(os.path.dirname(dest), exist_ok=True) 85 | #shutil.move(f, dest) 86 | #continue 87 | print('small', img.size) 88 | elif resized or mode_changed: 89 | print('re-writing image') 90 | dest = os.path.relpath(f, base_dir) 91 | dest = os.path.join(base_dir, 'resized', dest) 92 | os.makedirs(os.path.dirname(dest), exist_ok=True) 93 | shutil.move(f, dest) # move original 94 | extra = {} 95 | if 'icc_profile' in img.info: 96 | extra['icc_profile'] = img.info['icc_profile'] 97 | if 'exif' in img.info: 98 | extra['exif'] = img.info['exif'] 99 | img.save(f, 'jpeg', subsampling=1, quality=95, **extra) 100 | 101 | if not mode_changed: 102 | img = img.convert('RGB') 103 | s = Stat(img) 104 | mean = s.mean 105 | std = [x ** 0.5 for x in s.var] 106 | except Exception as e: 107 | print('Exception:', e) 108 | dest = os.path.relpath(f, base_dir) 109 | dest = os.path.join(base_dir, 'error', dest) 110 | #os.makedirs(os.path.dirname(dest), exist_ok=True) 111 | #shutil.move(f, dest) 112 | error_list.append((id_only, str(e))) 113 | continue 114 | 115 | cls_list.append(img_cls) 116 | id_list.append(img_id) 117 | size_list.append(img.size) 118 | mean_list.append(mean) 119 | std_list.append(std) 120 | format_list.append(fmt) 121 | # end for 122 | 123 | return cls_list, id_list, np.array(size_list), np.array(mean_list), np.array(std_list), format_list, error_list 124 | 125 | 126 | def process_dataset(name, filenames, base_dir, num_processes=20,): 127 | input_slices = [x.tolist() for x in np.array_split(filenames, num_processes)] 128 | pool = multiprocessing.Pool(num_processes) 129 | img_cls = [] 130 | img_ids = [] 131 | sizes = [] 132 | means = [] 133 | stds = [] 134 | formats = [] 135 | errors = [] 136 | for m_cls, m_ids, m_sizes, m_means, m_stds, m_fmts, m_err in pool.map( 137 | partial(process_imgs, base_dir=base_dir), input_slices): 138 | print(len(m_ids)) 139 | img_cls.extend(m_cls) 140 | img_ids.extend(m_ids) 141 | sizes.append(m_sizes) 142 | means.append(m_means) 143 | stds.append(m_stds) 144 | formats.extend(m_fmts) 145 | errors.extend(m_err) 146 | pool.close() 147 | 148 | print(errors) 149 | sizes = np.concatenate(sizes) 150 | means = np.concatenate(means) 151 | stds = np.concatenate(stds) 152 | 153 | num_s = sizes[(sizes < 56).any(axis=1)] 154 | num_l = sizes[(sizes > 896).any(axis=1)] 155 | print('small:', len(num_s), 'large:', len(num_l)) 156 | 157 | min_w = np.min(sizes[:, 0]) 158 | min_h = np.min(sizes[:, 1]) 159 | print('Minimum width, height:', min_w, min_h) 160 | print('Mean width, height', np.mean(sizes[:, 0]), np.mean(sizes[:, 1])) 161 | print('Med width, height', np.median(sizes[:, 0]), np.median(sizes[:, 1])) 162 | max_w = np.max(sizes[:, 0]) 163 | max_h = np.max(sizes[:, 1]) 164 | print('Max width, height:', max_w, max_h) 165 | 166 | avg_mean = np.mean(means, axis=0) 167 | avg_std = np.mean(stds, axis=0) 168 | print('Dataset mean:', avg_mean) 169 | print('Dataset std:', avg_std) 170 | 171 | fh = Counter(formats) 172 | print(fh) 173 | 174 | df = pd.DataFrame(data=OrderedDict( 175 | cls=img_cls, id=img_ids, width=sizes[:, 0], height=sizes[:, 1], 176 | mean_r=means[:, 0], mean_g=means[:, 1], mean_b=means[:, 2], 177 | std_r=stds[:, 0], std_g=stds[:, 1], std_b=stds[:, 2], 178 | fmt=formats, 179 | )) 180 | output_csv = '%s-info.csv' % name 181 | print('Writing %s with %d entries' % (output_csv, len(df.index))) 182 | df.to_csv(output_csv, index=False) 183 | 184 | 185 | BASE_DIR = '/data/in21k/' 186 | images_test = find_images(BASE_DIR) 187 | process_dataset('pp', images_test, BASE_DIR) 188 | #process_dataset('validation', images_validation) 189 | 190 | 191 | aa -------------------------------------------------------------------------------- /misc/resize.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import numpy as np 4 | import multiprocessing 5 | from PIL import Image 6 | 7 | 8 | BASE_DIR = '/data/old_in21k/resized/' 9 | EXCLUDE_DIR = '/data/in21k_resized/' 10 | 11 | 12 | samplings = { 13 | (1, 1, 1, 1, 1, 1): 0, 14 | (2, 1, 1, 1, 1, 1): 1, 15 | (2, 2, 1, 1, 1, 1): 2, 16 | } 17 | 18 | 19 | def process(f): 20 | dest = os.path.relpath(f, BASE_DIR) 21 | dest = os.path.join(EXCLUDE_DIR, 'xresized', dest) 22 | try: 23 | img = Image.open(f) 24 | fmt = img.format 25 | if hasattr(img, 'layer') and len(img.layer) == 3: 26 | sampling = img.layer[0][1:3] + img.layer[1][1:3] + img.layer[2][1:3] 27 | s = samplings.get(sampling, -1) 28 | else: 29 | s = -1 30 | if max(img.size) > 896: 31 | w, h = img.size 32 | if w > h: 33 | ratio = h / w 34 | wn = 896 35 | hn = int(wn * ratio) 36 | else: 37 | ratio = w / h 38 | hn = 896 39 | wn = int(hn * ratio) 40 | print(f'resizing {w}, {h} to {wn}, {hn}, sampling: {s} ') 41 | img = img.resize((wn, hn), Image.BICUBIC, reducing_gap=3) 42 | extra = {} 43 | if 'icc_profile' in img.info: 44 | extra['icc_profile'] = img.info['icc_profile'] 45 | if 'exif' in img.info: 46 | extra['exif'] = img.info['exif'] 47 | 48 | os.makedirs(os.path.dirname(dest), exist_ok=True) 49 | img.save(dest, 'jpeg', subsampling=1, quality=95, **extra) 50 | 51 | except Exception as e: 52 | print(e) 53 | 54 | 55 | def process_imgs(filenames): 56 | for f in filenames: 57 | process(f) 58 | 59 | 60 | num_processes = 20 61 | filenames = list(glob.glob(BASE_DIR + '**/*.JPEG', recursive=True)) 62 | input_slices = [x.tolist() for x in np.array_split(filenames, num_processes)] 63 | pool = multiprocessing.Pool(num_processes) 64 | pool.map(process_imgs, input_slices) 65 | 66 | -------------------------------------------------------------------------------- /tfds/__init__.py: -------------------------------------------------------------------------------- 1 | """imagenet12k dataset.""" 2 | 3 | -------------------------------------------------------------------------------- /tfds/helpers/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /tfds/imagenet22k.py: -------------------------------------------------------------------------------- 1 | """imagenet22k dataset.""" 2 | 3 | import tensorflow_datasets as tfds 4 | 5 | _DESCRIPTION = """ 6 | Description is **formatted** as markdown. 7 | 8 | It should also contain any processing which has been applied (if any), 9 | (e.g. corrupted example skipped, images cropped,...): 10 | """ 11 | 12 | _CITATION = """ 13 | """ 14 | 15 | _LABELS_FNAME = 'imagenet_22k_labels.txt' 16 | _LABELS_ALT_FNAME = 'imagenet_12k_labels.txt' 17 | _TRAIN_CSV = 'train_full.csv' 18 | _VALIDATION_CSV = 'val_12k.csv' 19 | 20 | 21 | class Imagenet22k(tfds.core.GeneratorBasedBuilder): 22 | """DatasetBuilder for imagenet22k dataset.""" 23 | 24 | VERSION = tfds.core.Version('1.0.0') 25 | RELEASE_NOTES = { 26 | '1.0.0': 'Initial release.', 27 | } 28 | 29 | def _info(self) -> tfds.core.DatasetInfo: 30 | """Returns the dataset metadata.""" 31 | # TODO(imagenet22k): Specifies the tfds.core.DatasetInfo object 32 | return tfds.core.DatasetInfo( 33 | builder=self, 34 | description=_DESCRIPTION, 35 | features=tfds.features.FeaturesDict({ 36 | # These are the features of your dataset like images, labels ... 37 | 'image': tfds.features.Image(shape=(None, None, 3)), 38 | 'label': tfds.features.ClassLabel(names=['no', 'yes']), 39 | 'label_12k': tfds.features.ClassLabel(names=['no', 'yes']), 40 | }), 41 | # If there's a common (input, target) tuple from the 42 | # features, specify them here. They'll be used if 43 | # `as_supervised=True` in `builder.as_dataset`. 44 | supervised_keys=('image', 'label'), # Set to `None` to disable 45 | homepage='https://dataset-homepage/', 46 | citation=_CITATION, 47 | ) 48 | 49 | def _split_generators(self, dl_manager: tfds.download.DownloadManager): 50 | """Returns SplitGenerators.""" 51 | 52 | # TODO(imagenet22k): Returns the Dict[split names, Iterator[Key, Example]] 53 | return { 54 | 'train': self._generate_examples(), 55 | 'validation': self._generate_examples(), 56 | } 57 | 58 | def _generate_examples(self, path): 59 | """Yields examples.""" 60 | # TODO(imagenet22k): Yields (key, example) tuples from the dataset 61 | for f in path.glob('*.jpeg'): 62 | yield 'key', { 63 | 'image': f, 64 | 'label': 'yes', 65 | } 66 | -------------------------------------------------------------------------------- /tfds/imagenet22k_test.py: -------------------------------------------------------------------------------- 1 | """imagenet12k dataset.""" 2 | 3 | import tensorflow_datasets as tfds 4 | from . import imagenet22k 5 | 6 | 7 | class Imagenet12kTest(tfds.testing.DatasetBuilderTestCase): 8 | """Tests for imagenet12k dataset.""" 9 | # TODO(imagenet12k): 10 | DATASET_CLASS = imagenet12k.Imagenet12k 11 | SPLITS = { 12 | 'train': 3, # Number of fake train example 13 | 'test': 1, # Number of fake test example 14 | } 15 | 16 | # If you are calling `download/download_and_extract` with a dict, like: 17 | # dl_manager.download({'some_key': 'http://a.org/out.txt', ...}) 18 | # then the tests needs to provide the fake output paths relative to the 19 | # fake data directory 20 | # DL_EXTRACT_RESULT = {'some_key': 'output_file1.txt', ...} 21 | 22 | 23 | if __name__ == '__main__': 24 | tfds.testing.test_main() 25 | -------------------------------------------------------------------------------- /wds/build_wds.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import io 3 | import math 4 | import os 5 | import json 6 | from functools import partial 7 | from itertools import accumulate, chain, repeat, tee 8 | 9 | import numpy as np 10 | import pandas as pd 11 | import webdataset as wds 12 | from PIL import Image 13 | from PIL.ImageStat import Stat 14 | 15 | from common.load_records import load_records 16 | 17 | 18 | def chunk(xs, n): 19 | assert n > 0 20 | L = len(xs) 21 | s, r = divmod(L, n) 22 | widths = chain(repeat(s + 1, r), repeat(s, n - r)) 23 | offsets = accumulate(chain((0,), widths)) 24 | b, e = tee(offsets) 25 | next(e) 26 | return [xs[s] for s in map(slice, b, e)] 27 | 28 | 29 | def write_shard( 30 | shard, 31 | input_dir, 32 | output_pattern, 33 | alt_label='', 34 | resize_short=False, 35 | max_img_size=None, 36 | min_img_size=56, 37 | include_stats=False, 38 | ): 39 | shard_id, input_records = shard 40 | ss = open(output_pattern % shard_id, 'wb') 41 | writer = wds.TarWriter(ss) 42 | if alt_label: 43 | alt_label = '_'.join(['label', alt_label]) 44 | 45 | success = (shard_id, []) 46 | error_list = [] 47 | for r in input_records: 48 | label = r['label'] 49 | label = label.item() if isinstance(label, np.integer) else int(label) 50 | output_record = dict(label=label) 51 | if alt_label: 52 | alt_label_val = r[alt_label] 53 | alt_label_val = alt_label_val.item() if isinstance(alt_label_val, np.integer) else int(alt_label_val) 54 | output_record[alt_label] = alt_label_val 55 | output_record['class_name'] = r['cls'] 56 | f = os.path.join(input_dir, r['filename']) 57 | try: 58 | img_stream = io.BytesIO(open(f, 'rb').read()) 59 | img = Image.open(img_stream) 60 | format_changed = img.format != 'JPEG' 61 | mode_changed = False 62 | if img.mode not in ("RGB", "L"): 63 | print('Mode', img.mode) 64 | mode_changed = True 65 | img = img.convert('RGB') 66 | 67 | w, h = img.size 68 | output_record['width'] = w 69 | output_record['height'] = h 70 | resized = False 71 | if max_img_size is not None: 72 | cmp_fn = min if resize_short else max 73 | cmp_size = cmp_fn(img.size) 74 | if cmp_size > max_img_size: 75 | scale = max_img_size / float(cmp_size) 76 | if scale != 1.0: 77 | wn, hn = tuple(round(d * scale) for d in (w, h)) 78 | print(f'resizing {w}, {h} to {wn}, {hn} ') 79 | img = img.resize((wn, hn), Image.BICUBIC, reducing_gap=3) 80 | resized = True 81 | output_record['orig_width'] = int(w) 82 | output_record['orig_height'] = int(h) 83 | output_record['width'] = int(wn) 84 | output_record['height'] = int(hn) 85 | 86 | if min_img_size and min(img.size) < min_img_size: 87 | print('skipping small', img.size) 88 | raise RuntimeError(f'Skipped. Image ({f}) too small ({img.size})') 89 | elif resized or mode_changed or format_changed: 90 | print('re-writing image', resized, mode_changed, format_changed) 91 | extra = {} 92 | if 'icc_profile' in img.info: 93 | extra['icc_profile'] = img.info['icc_profile'] 94 | if 'exif' in img.info: 95 | extra['exif'] = img.info['exif'] 96 | del img_stream 97 | img_stream = io.BytesIO() 98 | img.save(img_stream, 'JPEG', subsampling=1, quality=90, **extra) 99 | 100 | img_stream.seek(0) 101 | 102 | if include_stats: 103 | if not mode_changed: 104 | img = img.convert('RGB') 105 | s = Stat(img) 106 | output_record['mean'] = s.mean 107 | output_record['std'] = [x ** 0.5 for x in s.var] 108 | 109 | if 'key' in output_record: 110 | key = output_record.pop('key') 111 | else: 112 | key = os.path.splitext(os.path.basename(f))[0] 113 | 114 | writer.write(dict(__key__=key, jpg=img_stream.read(), json=output_record, cls=label)) 115 | 116 | except Exception as e: 117 | print('Exception:', e) 118 | error_list.append((r['filename'], str(e))) 119 | continue 120 | 121 | output_record['filename'] = os.path.basename(f) 122 | success[1].append(output_record) 123 | # end for 124 | 125 | writer.close() 126 | return success, error_list 127 | 128 | 129 | def process_dataset( 130 | records, 131 | dataset_name, 132 | split_name, 133 | input_dir, 134 | output_dir, 135 | alt_label='', 136 | num_processes=16, 137 | num_shards=2048, 138 | resize_short=True, 139 | max_img_size=None, 140 | min_img_size=56 141 | ): 142 | sharded_images_to_write = list(enumerate(chunk(records, num_shards))) 143 | shard_digits = math.ceil(math.log(num_shards) / math.log(10)) 144 | pattern = f'{dataset_name}-{split_name}-%0{shard_digits}d.tar' 145 | abs_pattern = os.path.join(output_dir, pattern) 146 | 147 | pool = multiprocessing.Pool(num_processes) 148 | success = [] 149 | errors = [] 150 | 151 | for m_success, m_err in pool.imap_unordered( 152 | partial( 153 | write_shard, 154 | input_dir=input_dir, 155 | output_pattern=abs_pattern, 156 | alt_label=alt_label, 157 | resize_short=resize_short, 158 | max_img_size=max_img_size, 159 | min_img_size=min_img_size, 160 | ), sharded_images_to_write): 161 | 162 | success.append(m_success) 163 | errors.extend(m_err) 164 | 165 | pool.close() 166 | print(errors) 167 | 168 | df = pd.DataFrame(success) 169 | output_csv = f'{dataset_name}-{split_name}-info.csv' 170 | output_csv = os.path.join(output_dir, output_csv) 171 | print('Writing %s with %d entries' % (output_csv, len(df.index))) 172 | df.to_csv(output_csv, index=False) 173 | 174 | success = sorted(success, key=lambda x: x[0]) 175 | filenames = [pattern % s[0] for s in success] 176 | info = dict( 177 | name=dataset_name, 178 | splits=dict(), 179 | ) 180 | split = dict( 181 | name=split_name, 182 | filenames=filenames, 183 | shard_lengths=[len(s[1]) for s in success], 184 | alt_label=None, 185 | ) 186 | split['num_samples'] = sum(split['shard_lengths']) 187 | info['splits'][split_name] = split 188 | if alt_label: 189 | alt_split = '_'.join([split_name, alt_label]) 190 | alt_label = '_'.join(['label', alt_label]) 191 | split = dict( 192 | name=alt_split, 193 | filenames=filenames, 194 | shard_lengths=[sum([ss[alt_label] >= 0 for ss in s[1]]) for s in success], 195 | alt_label=alt_label, 196 | ) 197 | split['num_samples'] = sum(split['shard_lengths']) 198 | info['splits'][alt_split] = split 199 | return info 200 | 201 | 202 | INPUT_DIR = '/data/in21k/' 203 | OUTPUT_DIR = '/data/in12k-wds' 204 | TRAIN_CSV = 'train_full.csv' 205 | VAL_CSV = 'val_12k.csv' 206 | SYNSET = 'imagenet-22k.txt' 207 | SYNSET_12k = 'imagenet-12k.txt' 208 | MIN_DIM = 56 209 | INCLUDE_12k = False 210 | 211 | train_records, val_records = load_records( 212 | train_csv=TRAIN_CSV, 213 | validation_csv=VAL_CSV, 214 | label_file=SYNSET, 215 | alt_label_name='label_12k' if INCLUDE_12k else '', 216 | alt_label_file=SYNSET_12k if INCLUDE_12k else '', 217 | min_img_size=MIN_DIM, 218 | ) 219 | 220 | train_info = process_dataset( 221 | records=train_records, 222 | dataset_name='imagenet22k', 223 | split_name='train', 224 | alt_label='12k', 225 | input_dir=INPUT_DIR, 226 | output_dir=OUTPUT_DIR, 227 | num_shards=4096, 228 | min_img_size=MIN_DIM, 229 | max_img_size=600, 230 | ) 231 | 232 | 233 | val_info = process_dataset( 234 | records=val_records, 235 | dataset_name='imagenet22k', 236 | split_name='validation', 237 | alt_label='12k', 238 | input_dir=INPUT_DIR, 239 | output_dir=OUTPUT_DIR, 240 | num_shards=512, 241 | min_img_size=MIN_DIM, 242 | max_img_size=600, 243 | ) 244 | 245 | for k, v in val_info['splits'].items(): 246 | train_info['splits'][k] = v 247 | 248 | with open(os.path.join(OUTPUT_DIR, 'info.json'), 'w') as f: 249 | json.dump(train_info, f, indent=4) 250 | 251 | with open(os.path.join(OUTPUT_DIR, 'info.yaml'), 'w') as f: 252 | import yaml 253 | yaml.safe_dump(train_info, f) 254 | -------------------------------------------------------------------------------- /wds/tfds_to_wds.py: -------------------------------------------------------------------------------- 1 | 2 | import io 3 | import json 4 | import math 5 | import multiprocessing 6 | import os 7 | import re 8 | import numpy as np 9 | import tensorflow as tf 10 | import webdataset as wds 11 | import pandas as pd 12 | from PIL import Image 13 | from glob import glob 14 | from functools import partial 15 | 16 | 17 | def write_shard( 18 | shard, 19 | output_pattern, 20 | map_synsets=None, 21 | ): 22 | shard_id, shard_file = shard 23 | 24 | raw_dataset = tf.data.TFRecordDataset(shard_file) 25 | 26 | image_feature_desc = { 27 | 'label': tf.io.FixedLenFeature([], tf.int64), 28 | 'file_name': tf.io.FixedLenFeature([], tf.string), 29 | 'image': tf.io.FixedLenFeature([], tf.string), 30 | } 31 | 32 | def _parse_image_function(example_proto): 33 | # Parse the input tf.train.Example proto using the dictionary above. 34 | return tf.io.parse_single_example(example_proto, image_feature_desc) 35 | 36 | parsed_image_dataset = raw_dataset.map(_parse_image_function) 37 | 38 | ss = open(output_pattern % shard_id, 'wb') 39 | writer = wds.TarWriter(ss) 40 | 41 | success = (shard_id, []) 42 | error_list = [] 43 | for r in parsed_image_dataset: 44 | label = r['label'].numpy() 45 | label = label.item() if isinstance(label, np.integer) else int(label) 46 | filename = r['file_name'].numpy().decode('utf-8') 47 | filename = os.path.basename(filename) 48 | key = os.path.splitext(filename)[0] 49 | print(filename) 50 | if map_synsets is not None: 51 | synset = map_synsets.get(filename) 52 | else: 53 | synset = filename.split('_')[0] 54 | #filename = os.path.join(synset, filename) # of form synset/filename 55 | 56 | print(filename, key) 57 | 58 | image_bytes = r['image'].numpy() 59 | output_record = dict(label=label) 60 | try: 61 | img = Image.open(io.BytesIO(image_bytes)) 62 | w, h = img.size 63 | output_record['width'] = w 64 | output_record['height'] = h 65 | output_record['filename'] = filename 66 | #print(output_record) 67 | 68 | writer.write(dict(__key__=key, jpg=image_bytes, json=output_record, cls=label)) 69 | 70 | except Exception as e: 71 | print('Exception:', e) 72 | error_list.append((filename, str(e))) 73 | continue 74 | 75 | success[1].append(output_record) 76 | # end for 77 | 78 | writer.close() 79 | return success, error_list 80 | 81 | 82 | def process_dataset( 83 | dataset_name, 84 | split_name, 85 | input_dir, 86 | output_dir, 87 | num_processes=16, 88 | map_synsets=None, 89 | ): 90 | input_pattern = f'**-{split_name}.tfrecord**' 91 | path_pattern = os.path.join(input_dir, input_pattern) 92 | files = glob(path_pattern) 93 | 94 | shards = [] 95 | num_shards = 0 96 | for f in sorted(files): 97 | mm = re.search(r'\btfrecord-(\d+)-of-(\d+)', f) 98 | shard_id = int(mm.group(1)) 99 | num_shards = int(mm.group(2)) 100 | shards.append((shard_id, f)) 101 | assert len(shards) == num_shards 102 | 103 | shard_digits = math.ceil(math.log(len(shards)) / math.log(10)) 104 | pattern = f'{dataset_name}-{split_name}-%0{shard_digits}d.tar' 105 | abs_pattern = os.path.join(output_dir, pattern) 106 | 107 | pool = multiprocessing.Pool(num_processes) 108 | success = [] 109 | errors = [] 110 | 111 | for m_success, m_err in pool.imap_unordered( 112 | partial( 113 | write_shard, 114 | output_pattern=abs_pattern, 115 | map_synsets=map_synsets, 116 | ), shards): 117 | 118 | success.append(m_success) 119 | errors.extend(m_err) 120 | 121 | pool.close() 122 | print(errors) 123 | 124 | df = pd.DataFrame(success) 125 | output_csv = f'{dataset_name}-{split_name}-info.csv' 126 | output_csv = os.path.join(output_dir, output_csv) 127 | print('Writing %s with %d entries' % (output_csv, len(df.index))) 128 | df.to_csv(output_csv, index=False) 129 | 130 | success = sorted(success, key=lambda x: x[0]) 131 | filenames = [pattern % s[0] for s in success] 132 | info = dict( 133 | name=dataset_name, 134 | splits=dict(), 135 | ) 136 | split = dict( 137 | name=split_name, 138 | filenames=filenames, 139 | shard_lengths=[len(s[1]) for s in success], 140 | ) 141 | split['num_samples'] = sum(split['shard_lengths']) 142 | info['splits'][split_name] = split 143 | return info 144 | 145 | 146 | INPUT_DIR = '/data/in12k-tfds/imagenet12k/1.0.0' 147 | OUTPUT_DIR = '/data/temp' 148 | 149 | #synset_map = pd.read_csv('./test.csv') 150 | #synset_map = dict(zip(synset_map.iloc[:, 0], synset_map.iloc[:, 1])) 151 | #print(synset_map) 152 | 153 | validation_info = process_dataset( 154 | dataset_name='imagenet1k', 155 | split_name='validation', 156 | input_dir=INPUT_DIR, 157 | output_dir=OUTPUT_DIR, 158 | # map_synsets=synset_map, 159 | ) 160 | 161 | train_info = process_dataset( 162 | dataset_name='imagenet1k', 163 | split_name='train', 164 | input_dir=INPUT_DIR, 165 | output_dir=OUTPUT_DIR, 166 | ) 167 | 168 | print(train_info) 169 | 170 | 171 | 172 | for k, v in validation_info['splits'].items(): 173 | train_info['splits'][k] = v 174 | 175 | with open(os.path.join(OUTPUT_DIR, 'info.json'), 'w') as f: 176 | json.dump(train_info, f, indent=4) 177 | --------------------------------------------------------------------------------