Package: img2dataset
img2datasetEasily turn large sets of image urls to an image dataset.
Can download, resize and package 100M urls in 20h on one machine.Also supports saving captions for url+caption datasets.If you believe in making reusable tools to make data easy to use for ML and you would like to contribute, please join theDataToMLchat.Installpipinstallimg2datasetFor better performance, it's highly recommended to set up a fast dns resolver, seethis sectionOpt-out directivesWebsites can pass the http headersX-Robots-Tag: noai,X-Robots-Tag: noindex,X-Robots-Tag: noimageaiandX-Robots-Tag: noimageindexBy default img2dataset will ignore images with such headers.To disable this behavior and download all images, you may pass --disallowed_header_directives '[]'SeeAI use impactto understand better why you may decide to enable or disable this feature.ExamplesExample of datasets to download with example commands are available in thedataset_examplesfolder. In particular:mscoco600k image/text pairs that can be downloaded in 10minsbucaptions860K image/text pairs can be downloaded in 20 mins.cc3m3M image/text pairs that can be downloaded in one hourcc12m12M image/text pairs that can be downloaded in five hourlaion400m400M image/text pairs that can be downloaded in 3.5 dayslaion5B5B image/text pairs that can be downloaded in 7 days using 10 nodeslaion-aestheticLaion aesthetic is a 120M laion5B subset with aesthetic > 7 pwatermark < 0.8 punsafe < 0.5laion-artLaion aesthetic is a 8M laion5B subset with aesthetic > 8 pwatermark < 0.8 punsafe < 0.5laion-cocoLaion-COCO is a 600M subset of LAION2B-EN, captioned with an ensemble of BLIP L/14 and 2 CLIP versions (L/14 and RN50x64).laion-high-resolutionLaion high resolution is a 170M resolution >= 1024x1024 subset of laion5Blaion-faceLaion face is the human face subset of LAION-400M for large-scale face pretraining. It has 50M image-text pairs.coyo-700mCOYO is a large-scale dataset that contains 747M image-text pairs as well as many other meta-attributes to increase the usability to train various models.commonpoolCommonPool is a large-scale dataset collected from CommonCrawl containing 12.8B image-text pairs.datacomp-1bDataComp-1B is a large-scale dataset with 1.4B image-text pairs filtered from CommonPool.For all these examples, you may want to tweak the resizing to your preferences. The default is 256x256 with white borders.
See options below.UsageFirst get some image url list. For example:echo'https://placekitten.com/200/305'>>myimglist.txtecho'https://placekitten.com/200/304'>>myimglist.txtecho'https://placekitten.com/200/303'>>myimglist.txtThen, run the tool:img2dataset--url_list=myimglist.txt--output_folder=output_folder--thread_count=64--image_size=256The tool will then automatically download the urls, resize them, and store them with that format:output_folder00000000000000.jpg000000001.jpg000000002.jpgor as this format if choosing webdataset:output_folder00000.tar containing:000000000.jpg000000001.jpg000000002.jpgwith each number being the position in the list. The subfolders avoids having too many files in a single folder.Ifcaptionsare provided, they will be saved as 0.txt, 1.txt, ...This can then easily be fed into machine learning training or any other use case.Also .json files named 0.json, 1.json,... are saved with these keys:urlcaptionkey of the form 000010005 : the first 5 digits are the shard id, the last 4 are the index in the shardstatus : whether the download succeedederror_messagewidthheightoriginal_widthoriginal_heightexifAlso a .parquet file will be saved with the same name as the subfolder/tar files containing these same metadata.
It can be used to analyze the results efficiently..json files will also be saved with the same name suffixed by _stats, they contain stats collected during downloading (download time, number of success, ...)Python examplesCheckout these examples to call this as a lib:simple_example.pypyspark_example.pydistributed img2dataset tutorialAPIThis module exposes a single functiondownloadwhich takes the same arguments as the command line tool:url_listA file with the list of url of images to download. It can be a folder of such files. (required)image_sizeThe size to resize image to (default256)output_folderThe path to the output folder. (default"images")processes_countThe number of processes used for downloading the pictures. This is important to be high for performance. (default1)thread_countThe number of threads used for downloading the pictures. This is important to be high for performance. (default256)resize_modeThe way to resize pictures, can be no, border or keep_ratio (defaultborder)nodoesn't resize at allborderwill make the image image_size x image_size and add a borderkeep_ratiowill keep the ratio and make the smallest side of the picture image_sizekeep_ratio_largestwill keep the ratio and make the largest side of the picture image_sizecenter_cropwill keep the ratio and center crop the largest side so the picture is squaredresize_only_if_biggerresize pictures only if bigger that the image_size (defaultFalse)upscale_interpolationkind of upscale interpolation used for resizing (default"lanczos")downscale_interpolationkind of downscale interpolation used for resizing (default"area")encode_qualityencode quality from 0 to 100, when using png it is the compression factor from 0 to 9 (default95)encode_formatencode format (defaultjpg)jpgjpeg formatpngpng formatwebpwebp formatskip_reencodewhether to skip reencoding if no resizing is done (defaultFalse)output_formatdecides how to save pictures (defaultfiles)filessaves as a set of subfolder containing pictureswebdatasetsaves as tars containing picturesparquetsaves as parquet containing pictures as bytestfrecordsaves as tfrecord containing pictures as bytesdummydoes not save. Useful for benchmarksinput_formatdecides how to load the urls (defaulttxt)txtloads the urls as a text file of url, one per linetxt.gzloads the urls as a compressed (gzip) txt.gz with a list of url, one per linecsvloads the urls and optional caption as a csvcsv.gzloads the urls and optional caption, as a compressed (gzip) csv.gztsvloads the urls and optional caption as a tsvtsv.gzloads the urls and optional caption, as a compressed (gzip) tsv.gzjsonloads the urls and optional caption as a jsonjson.gzloads the urls and optional caption, as a compressed (gzip) json.gzjsonlloads the urls and optional caption as a jsonl. seejsonlinesfor morejsonl.gzloads the urls and optional caption, as a compressed (gzip) jsonl.gz. seejsonlinesfor moreparquetloads the urls and optional caption as a parqueturl_colthe name of the url column for parquet and csv (defaulturl)caption_colthe name of the caption column for parquet and csv (defaultNone)bbox_colthe name of the bounding box column. Bounding boxes are assumed to have format[x_min, y_min, x_max, y_max], with all elements being floats in[0,1](relative to the size of the image). IfNone, then no bounding box blurring is performed (defaultNone)number_sample_per_shardthe number of sample that will be downloaded in one shard (default10000)extract_exifif true, extract the exif information of the images and save it to the metadata (defaultTrue)save_additional_columnslist of additional columns to take from the csv/parquet files and save in metadata files (defaultNone)timeoutmaximum time (in seconds) to wait when trying to download an image (default10)enable_wandbwhether to enable wandb logging (defaultFalse)wandb_projectname of W&B project used (defaultimg2dataset)oom_shard_countthe order of magnitude of the number of shards, used only to decide what zero padding to use to name the shard files (default5)compute_hashthe hash of raw images to compute and store in the metadata, one ofNone,md5,sha256,sha512(defaultsha256)verify_hashif notNone, then this is a list of two elements that will be used to verify hashes based on the provided input. The first element of this list is the label of the column containing the hashes in the input file, while the second one is the type of the hash that is being checked (defaultNone)distributorchoose how to distribute the downloading (defaultmultiprocessing)multiprocessinguse a multiprocessing pool to spawn processespysparkuse a pyspark session to create workers on a spark cluster (see details below)rayuse a ray cluster. See ray example.subjob_sizethe number of shards to download in each subjob supporting it, a subjob can be a pyspark job for example (default1000)retriesnumber of time a download should be retried (default0)disable_all_reencodingif set to True, this will keep the image files in their original state with no resizing and no conversion, will not even check if the image is valid. Useful for benchmarks. To use only if you plan to post process the images by another program and you have plenty of storage available. (defaultFalse)min_image_sizeminimum size of the image to download (default0)max_image_areamaximum area of the image to download (defaultinf)max_aspect_ratiomaximum aspect ratio of the image to download (defaultinf)incremental_modeCan be "incremental", "overwrite" or "extend". For "incremental", img2dataset will download all the shards that were not downloaded, for "overwrite" img2dataset will delete recursively the output folder then start from zero, for "extend" img2dataset will download shards from the next available shard number (defaultincremental)max_shard_retryNumber of time to retry failed shards at the end (default1)user_agent_tokenAdditional identifying token that will be added to the User-Agent header sent with HTTP requests to download images; for example: "img2downloader". (defaultNone)disallowed_header_directivesList of X-Robots-Tags header directives that, if present in HTTP response when downloading an image, will cause the image to be excluded from the output dataset. To ignore x-robots-tags, pass '[]'. (default '["noai", "noimageai", "noindex", "noimageindex"]')Incremental modeIf a first download got interrupted for any reason, you can run again with --incremental "incremental" (this is the default) and using the same output folder , the same number_sample_per_shard and the same input urls, and img2dataset will complete the download.Output format choiceImg2dataset support several formats. There are trade off for which to choose:files: this is the simplest one, images are simply saved as files. It's good for up to 1M samples on a local file system. Beyond that performance issues appear very fast. Handling more than a million files in standard filesystem does not work well.webdataset: webdataset format saves samples in tar files, thanks towebdatasetlibrary, this makes it possible to load the resulting dataset fast in both pytorch, tensorflow and jax. Choose this for most use cases. It works well for any filesystemparquet: parquet is a columnar format that allows fast filtering. It's particularly easy to read it using pyarrow and pyspark. Choose this if the rest of your data ecosystem is based on pyspark.petastormcan be used to read the data but it's not as easy to use as webdatasettfrecord: tfrecord is a protobuf based format. It's particularly easy to use from tensorflow and usingtf data. Use this if you plan to use the dataset only in the tensorflow ecosystem. The tensorflow writer does not use fsspec and as a consequence supports only a limited amount of filesystem, including local, hdfs, s3 and gcs. It is also less efficient than the webdataset writer when writing to other filesystems than local, losing some 30% performance.Encode format choiceImages can be encoded in jpeg, png or webp, with different quality settings.Here are a few comparisons of space used for 1M images at 256 x 256:formatqualitycompressionsize (GB)jpg100N/A54.2jpg95N/A29.9pngN/A0187.9pngN/A997.7webp100N/A31.0webp95N/A23.8Notes:jpeg at quality 100 is NOT losslesspng format is losslesswebp at quality >100 is lossless (see OpenCV Docs)same quality scale between formats does not mean same image qualityFiltering the datasetWhenever feasible, you should pre-filter your dataset prior to downloading.If needed, you can use:--min_image_size SIZE : to filter out images with one side smaller than SIZE--max_image_area SIZE : to filter out images with area larger than SIZE--max_aspect_ratio RATIO : to filter out images with an aspect ratio greater than RATIOWhen filtering data, it is recommended to pre-shuffle your dataset to limit the impact on shard size distribution.Hashes and securitySome dataset (for example laion5B) expose hashes of original images.If you want to be extra safe, you may automatically drop out the images that do not match theses hashes.
In that case you can use--compute_hash "md5" --verify_hash '["md5","md5"]'Some of those images are actually still good but have been slightly changed by the websites.How to tweak the optionsThe default values should be good enough for small sized dataset. For larger ones, these tips may help you get the best performance:set the processes_count as the number of cores your machine hasincrease thread_count as long as your bandwidth and cpu are below the limitsI advise to set output_format to webdataset if your dataset has more than 1M elements, it will be easier to manipulate few tars rather than million of fileskeeping metadata to True can be useful to check what items were already saved and avoid redownloading themTo benchmark your system, and img2dataset interactions with it, it may be interesting to enable these options (only for testing, not for real downloads)--output_format dummy : will not save anything. Good to remove the storage bottleneck--disable_all_reencoding True : will not reencode anything. Good to remove the cpu bottleneck
When both these options are enabled, the only bottlenecks left are network related: eg dns setup, your bandwidth or the url servers bandwidth.File system supportThanks tofsspec, img2dataset supports reading and writing files inmany file systems.
To use it, simply use the prefix of your filesystem before the path. For examplehdfs://,s3://,http://,gcs://,ssh://orhf://(includes aDataset Viewer).
Some of these file systems require installing an additional package (for example s3fs for s3, gcsfs for gcs,fsspec/sshfsfor ssh,huggingface_hubfor hf).
See fsspec doc for all the details.If you need specific configuration for your filesystem, you may handle this problem by using thefsspec configuration systemthat makes it possible to create a file such as.config/fsspec/s3.jsonand have information in it such as:{"s3":{"client_kwargs":{"endpoint_url":"https://some_endpoint","aws_access_key_id":"your_user","aws_secret_access_key":"your_password"}}}Which may be necessary if using s3 compatible file systems such asminio. That kind of configuration also work for all other fsspec-supported file systems.Distribution modesImg2dataset supports several distributors.multiprocessing which spawns a process pool and use these local processes for downloadingpyspark which spawns workers in a spark pool to do the downloadingmultiprocessing is a good option for downloading on one machine, and as such it is the default.
Pyspark lets img2dataset use many nodes, which makes it as fast as the number of machines.
It can be particularly useful if downloading datasets with more than a billion image.pyspark configurationIn order to use img2dataset with pyspark, you will need to do this:pip install pysparkuse the--distributor pysparkoptiontweak the--subjob_size 1000option: this is the number of images to download in each subjob. Increasing it will mean a longer time of preparation to put the feather files in the temporary dir, a shorter time will mean sending less shards at a time to the pyspark job.By default a local spark session will be created.
You may want to create a custom spark session depending on your specific spark cluster.
To do that checkpyspark_example.py, there you can plug your custom code to create a spark session, then
run img2dataset which will use it for downloading.To create a spark cluster check thedistributed img2dataset tutorialIntegration with Weights & BiasesTo enable wandb, use the--enable_wandb=Trueoption.Performance metrics are monitored throughWeights & Biases.In addition, most frequent errors are logged for easier debugging.Other features are available:logging of environment configuration (OS, python version, CPU count, Hostname, etc)monitoring of hardware resources (GPU/CPU, RAM, Disk, Networking, etc)custom graphs and reportscomparison of runs (convenient when optimizing parameters such as number of threads/cpus)When running the script for the first time, you can decide to either associate your metrics to your account or log them anonymously.You can also log in (or create an account) before by runningwandb login.Road mapThis tool works very well in the current state for up to 100M elements. Future goals include:a benchmark for 1B pictures which may requirefurther optimization on the resizing partbetter multi node supportintegrated support for incremental support (only download new elements)Architecture notesThis tool is designed to download pictures as fast as possible.
This put a stress on various kind of resources. Some numbers assuming 1350 image/s:Bandwidth: downloading a thousand average image per second requires about 130MB/sCPU: resizing one image may take several milliseconds, several thousand per second can use up to 16 coresDNS querying: million of urls mean million of domains, default OS setting usually are not enough. Setting up a local bind9 resolver may be requiredDisk: if using resizing, up to 30MB/s write speed is necessary. If not using resizing, up to 130MB/s. Writing in few tar files make it possible to use rotational drives instead of a SSD.With these information in mind, the design choice was done in this way:the list of urls is split in K shards. K is chosen such that a shard has a reasonable size on disk (for example 256MB), by default K = 10000N processes are started (using multiprocessing process pool)each process starts M threads. M should be maximized in order to use as much network as possible while keeping cpu usage below 100%.each of this thread download 1 image and returns itthe parent thread handle resizing (which means there is at most N resizing running at once, using up the cores but not more)the parent thread saves to a tar file that is different from other processThis design make it possible to use the CPU resource efficiently by doing only 1 resize per core, reduce disk overhead by opening 1 file per core, while using the bandwidth resource as much as possible by using M thread per process.Also seearchitecture.mdfor the precise split in python modules.Setting up a high performance dns resolverTo get the best performances with img2dataset, using an efficient dns resolver is needed.knot resolver can run in parallelbind resolver is the historic resolver and is mono core but very optimizedSetting up a knot resolverFollowthe official quick startor run this on ubuntu:install knot withwgethttps://secure.nic.cz/files/knot-resolver/knot-resolver-release.deb
sudodpkg-iknot-resolver-release.deb
sudoaptupdate
sudoaptinstall-yknot-resolver
sudosh-c'echo `hostname -I` `hostname` >> /etc/hosts'sudosh-c'echo nameserver 127.0.0.1 > /etc/resolv.conf'sudosystemctlstopsystemd-resolvedthen start 4 instances withsudosystemctlstartkresd@1.service
sudosystemctlstartkresd@2.service
sudosystemctlstartkresd@3.service
sudosystemctlstartkresd@4.serviceCheck it works withdig@localhostgoogle.comSetting up a bind9 resolverIn order to keep the success rate high, it is necessary to use an efficient DNS resolver.
I tried several options: systemd-resolved, dnsmaskq and bind9 and reached the conclusion that bind9 reaches the best performance for this use case.
Here is how to set this up on Ubuntu. Run:sudoaptinstallbind9
sudovim/etc/bind/named.conf.optionsAnd add this inoptions:recursive-clients 10000;
	resolver-query-timeout 30000;
	max-clients-per-query 10000;
	max-cache-size 2000m;Then, run:sudosystemctlrestartbind9echonameserver127.0.0.1|sudotee-a/etc/resolv.confThis will make it possible to keep an high success rate while doing thousands of dns queries.
You may also want tosetup bind9 loggingin order to check that few dns errors happen.AI use impactimg2dataset is used to retrieve images from the web and make them easily available for ML use cases. Use cases involve:doing inference and indexing to better understand what is in the web (https://rom1504.github.io/clip-retrieval/is an example of this)training modelsModels that can be trained using image/text datasets include:CLIP: an image understanding model that allow for example to know whether an image is safe, aesthetic, what animal it contains, ...text to image models: generating images based on textThere is a lot of discussions regarding the consequences of text to image models. Some opinions include:AI art is democratizing art and letting hundred of millions of people express themselves through art. Making art much more prevalent and uniqueAI models should not be trained on images that creator do not want to shareThe opt out directive try to let creators that do not want to share their art not be used for indexing and for training.For developmentEither locally, or ingitpod(doexport PIP_USER=falsethere)Setup a virtualenv:python3-mvenv.envsource.env/bin/activate
pipinstall-e.to run tests:pipinstall-rrequirements-test.txtthenmakelint
maketestYou can usemake blackto reformat the codepython -m pytest -x -s -v tests -k "dummy"to run a specific testBenchmarks10000 image benchmarkcdtests/test_files
bashbenchmark.sh18M image benchmarkDownload crawling at home first part, then:cdtests
bashlarge_bench.shIt takes 3.7h to download 18M pictures1350 images/s is the currently observed performance. 4.8M images per hour, 116M images per 24h.36M image benchmarkdownloading 2 parquet files of 18M items (result 936GB) took 7h24
average of 1345 image/s190M benchmarkdownloading 190M images from thecrawling at home datasettook 41h (result 5TB)
average of 1280 image/s5B benchmarkdownloading 5.8B images from thelaion5B datasettook 7 days (result 240TB), average of 9500 sample/s on 10 machines,technical detailsCitation@misc{beaumont-2021-img2dataset,author={Romain Beaumont},title={img2dataset: Easily turn large sets of image urls to an image dataset},year={2021},publisher={GitHub},journal={GitHub repository},howpublished={\url{https://github.com/rom1504/img2dataset}}}