# Vision utils


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Downloading images

[`download_images`](https://docs.fast.ai/vision/vision.utils.html#download_images)
uses random UUID filenames by default. With `preserve_filename=True`, it
uses the URL’s stem. It adds a numeric suffix if a file with the same
filename already exists in `dest`.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L41"
target="_blank" style="float:right; font-size:smaller">source</a>

### download_images

``` python
def download_images(
    dest, url_file:NoneType=None, urls:NoneType=None, max_pics:int=1000, n_workers:int=8, timeout:int=4,
    preserve_filename:bool=False
):
```

*Download images listed in text file `url_file` to path `dest`, at most
`max_pics`*

Pass URLs in `urls` or use `url_file` with one URL per line.
[`download_images`](https://docs.fast.ai/vision/vision.utils.html#download_images)
downloads them in threads. It silently skips failed downloads.

## Verifying images

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L50"
target="_blank" style="float:right; font-size:smaller">source</a>

### verify_image

``` python
def verify_image(
    fn
):
```

*Confirm that `fn` can be opened*

[`verify_image`](https://docs.fast.ai/vision/vision.utils.html#verify_image)
uses PIL’s `draft` mode to decode JPEGs at reduced resolution. This
keeps verification fast even for large images. It returns `False` if
opening or decoding the file raises an exception.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L60"
target="_blank" style="float:right; font-size:smaller">source</a>

### verify_images

``` python
def verify_images(
    fns
):
```

*Find images in `fns` that can’t be opened*

Remove files that
[`verify_images`](https://docs.fast.ai/vision/vision.utils.html#verify_images)
cannot open:

``` python
with tempfile.TemporaryDirectory() as d:
    d = Path(d)
    shutil.copy('../images/puppy.jpg', d)
    (d/'bad.jpg').write_text('not an image')
    failed = verify_images(get_image_files(d))
    test_eq(failed, [d/'bad.jpg'])
    failed.map(Path.unlink)
    test_eq(get_image_files(d), [d/'puppy.jpg'])
```

## Resizing images

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L65"
target="_blank" style="float:right; font-size:smaller">source</a>

### resize_to

``` python
def resize_to(
    img, targ_sz, use_min:bool=False
):
```

*Size to resize to, to hit `targ_sz` at same aspect ratio, in PIL coords
(i.e w*h)\*

[`resize_to`](https://docs.fast.ai/vision/vision.utils.html#resize_to)
calculates dimensions at the original aspect ratio. By default, the
larger side equals `targ_sz` and the result fits inside a `targ_sz`
square. With `use_min=True`, the smaller side equals `targ_sz` and the
result covers that square. The input needs a PIL-style `size` attribute:

``` python
class _FakeImg():
    def __init__(self, size): self.size=size

img = _FakeImg((200,500))
test_eq(resize_to(img, 400), [160,400])
test_eq(resize_to(img, 400, use_min=True), [400,1000])
```

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L73"
target="_blank" style="float:right; font-size:smaller">source</a>

### resize_image

``` python
def resize_image(
    file, # Image path, relative to `src`
    dest, # Output directory
    src:str='.', # Directory that `file` is relative to
    max_size:NoneType=None, # Resize so the larger side is at most this many pixels
    n_channels:int=3, # Convert to RGB when 3
    ext:NoneType=None, # Output suffix, e.g. '.png'; default keeps the original
    img_format:NoneType=None, # PIL format for `save`; default inferred from the suffix
    resample:PIL.Image.Resampling=<Resampling.BILINEAR: 2>, # PIL resampling filter
    resume:bool=False, # Skip files already present in `dest`?
    **kwargs
):
```

*Resize file to dest to max_size*

[`resize_image`](https://docs.fast.ai/vision/vision.utils.html#resize_image)
re-encodes files that exceed `max_size` or have a different number of
channels from `n_channels`. It copies other files unchanged to `dest`,
unless source and destination are the same. Use `resume=True` to skip
existing destination files when resuming an interrupted run.

Resize `puppy.jpg` to a maximum side of 400 pixels:

``` python
file = 'puppy.jpg'
dest = Path('.')
resize_image(file, dest, src='images', max_size=400)
im = Image.open(dest/file)
test_eq(im.shape[1],400)
(dest/file).unlink()
```

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L107"
target="_blank" style="float:right; font-size:smaller">source</a>

### resize_images

``` python
def resize_images(
    path, # Directory of images
    max_workers:int=4, # Parallel workers; 0 runs in the current process
    max_size:NoneType=None, # Resize so the larger side is at most this many pixels
    recurse:bool=False, # Include subdirectories?
    dest:pathlib.PosixPath=Path('.'), # Output directory
    n_channels:int=3, # Convert to RGB when 3
    ext:NoneType=None, # Output suffix, e.g. '.png'; default keeps the original
    img_format:NoneType=None, # PIL format for `save`; default inferred from the suffix
    resample:PIL.Image.Resampling=<Resampling.BILINEAR: 2>, # PIL resampling filter
    resume:NoneType=None, # Skip files already present in `dest`?
    **kwargs
):
```

*Resize the images in `path` to `dest`, so the larger side is at most
`max_size`*

[`resize_images`](https://docs.fast.ai/vision/vision.utils.html#resize_images)
processes images in parallel and preserves the directory structure under
`dest`:

``` python
with tempfile.TemporaryDirectory() as d:
    dest = Path(d)/'resized_images'
    resize_images('images', max_size=100, dest=dest, max_workers=0, recurse=True)
```

## Image search

Microsoft has retired the Bing Image Search API that earlier versions of
these functions, and the fastai book, relied on. These functions use
[SerpApi](https://serpapi.com) instead, which serves Bing and other
engines’ results through one API. Its free plan allows 250 searches a
month, and each page of 35 Bing results counts as one search, so a
150-image query costs 5.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L130"
target="_blank" style="float:right; font-size:smaller">source</a>

### search_images_serpapi

``` python
def search_images_serpapi(
    term, # Search query
    engine:str='bing_images', # Any SerpApi image engine, e.g. 'google_images'
    key:NoneType=None, # SerpApi key; default `SERPAPI_KEY` environment variable
    max_images:int=150, # Stop after this many URLs
):
```

*Image URLs for `term` from SerpApi’s `engine`, following pagination up
to `max_images`*

[`search_images_serpapi`](https://docs.fast.ai/vision/vision.utils.html#search_images_serpapi)
follows pagination links until it has `max_images` URLs or there are no
more pages. It raises HTTP errors rather than returning partial results.
Pass `engine='google_images'` to search Google images instead of Bing.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/vision/utils.py#L151"
target="_blank" style="float:right; font-size:smaller">source</a>

### search_images_bing

``` python
def search_images_bing(
    term, key:NoneType=None, max_images:int=150
):
```

*Bing image URLs for `term`, via SerpApi*

``` python
urls = search_images_bing('grizzly bear', max_images=40)
len(urls), urls[0]
```

Download the search results and remove files that fail verification:

``` python
with tempfile.TemporaryDirectory() as d:
    download_images(d, urls=urls[:10])
    fns = get_image_files(d)
    failed = verify_images(fns)
    failed.map(Path.unlink)
len(fns), len(failed)
```
