GithubHelp home page GithubHelp logo

yolov5-fastapi-demo's Introduction

yolov5-fastapi-demo

This is a demo FastAPI app that allows a user to upload image(s), perform inference using a pretrained YOLOv5 model, and receive results in JSON format. This repo also includes Jinja2 HTML templates, so you can access this interface through a web browser at localhost:8000.

image

Install Requirements

Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7 (per https://github.com/ultralytics/yolov5).

To install run:

pip install -r requirements.txt

Minimal FastAPI Example

See the minimal_client_server_example folder for a minimal client/server wrapper of YOLOv5 with FastAPI and HTML forms.

Again, you can try this out by:

  1. Running the server with python server_minimal.py or uvicorn server_minimal:app --reload
  2. Test the server with python client_minimal.py, navigating to localhost:8000 in your web browser or localhost:8000/docs -> POST Request -> Try It Out

Inference Methods

You can initialize the server with python server.py (use --help for other args) or uvicorn server:app --reload

You can test the server a couple of ways:

  1. Using client.py - this is a basic example of using the Requests library to upload a batch of images + model name to localhost:8000/detect/ and receive JSON inference results.
  2. Open localhost:8000 in your web browser, use the web form to upload image(s) and select a model, then click submit. You should see inference results displayed in the web browser shortly.
  3. Open http://localhost:8000/drag_and_drop_detect in your web browser, use the drag and drop interface to upload an image, and the image + bounding boxes will be rendered via Javascript.

Models will automatically be downloaded the first time they are used and are cached on disc.

city_street_results

API Documentation

API endpoint documentation is auto-generated in localhost:8000/docs. The general idea is that humans use the "/" route (HTML form + inference results displayed in the browser) and programs use the "/detect/" API route to receive JSON inference results.

Developer Notes

Server.py

Contains the FastAPI server code and helper functions.

Jinja2 Templates (/templates folder)

File Description
layout.html Base template with navbar that is common to all pages. home.html and drag_and_drop_detect.html both extend this template.
home.html Basic web form for uploading images, model selection and inference size to the server. The server gets the YOLO results and renders a bbox image, then returns the results by plugging them into the jinja2 template templates/show_results.html. This is overly fancy, but I wanted to demonstrate how to do this - if you want just JSON results see the minimal client-server example.
drag_and_drop_detect.html This implements a Drag & Drop interface to upload images. Once dropped onto the dropzone, the image and parameters are sent to the server's /detect endpoint which returns JSON results. The JSON results are then used to render the image + bboxes in the web browser as seen in the Inference Methods section above. The box labels are raised above the box outline such that the labels don't overlap with each other.

Credits

This repository is a wrapper around YOLOv5 from Ultralytics: https://github.com/ultralytics/yolov5

Also modified the results_to_json function from the original here: https://gist.github.com/decent-engineer-decent-datascientist/81e04ad86e102eb083416e28150aa2a1

yolov5-fastapi-demo's People

Contributors

welkinu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

yolov5-fastapi-demo's Issues

I want to integrate my custom model

I want to integrate my custom model into this .I have my best.pt file. I don't know how to do this .can you guide me how to do this?Thanks in advance!

load model from hub only once

I'm not familiar with FastAPI (only Starlette & Flask) but could we avoid calling torch.hub.load() on every request function? I think the model could be loaded once and used then in the different functions.

Error on loading custom model

I am gettting RuntimeError('Cannot find callable {} in hubconf'.format(model)), RuntimeError: Cannot find callable best.pt in hubconf when using my custom model.

According to PyTorch docs, I changed the line to

torch.hub.load('ultralytics/yolov5', 'custom', path_or_model='best.pt')

Not able to solve this error

BUG: passing files to yolov5 model from fastapi errors

Thank you for this demo!

Demo with fastapi async isn't playing nicely with yolov5 for me. The images being sent to the yolov5 model appear to not have a file path associated with them.

Works fine if I change the code to pass a url to an image.
Detects fine if I change the code to read in a file non-async.
I can also use yolov5 fine outside fastapi.

Error trace:

Adding autoShape... 
INFO:     127.0.0.1:58935 - "POST / HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/routing.py", line 201, in app
    raw_response = await run_endpoint_function(
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/routing.py", line 148, in run_endpoint_function
    return await dependant.call(**values)
  File "/Users/jeffhale/Dropbox/DS/repos/fastapi/yolov5-fastapi-demo/server_new.py", line 168, in detect_via_web_form
    results = model_dict[model_name](
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/Users/jeffhale/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 204, in forward
    files.append(Path(im.filename).with_suffix('.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg')
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/pathlib.py", line 892, in with_suffix
    raise ValueError("%r has an empty name" % (self,))
ValueError: PosixPath('.') has an empty name
Exception in ASGI application
Traceback (most recent call last):
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/routing.py", line 201, in app
    raw_response = await run_endpoint_function(
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/fastapi/routing.py", line 148, in run_endpoint_function
    return await dependant.call(**values)
  File "/Users/jeffhale/Dropbox/DS/repos/fastapi/yolov5-fastapi-demo/server_new.py", line 168, in detect_via_web_form
    results = model_dict[model_name](
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/Users/jeffhale/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 204, in forward
    files.append(Path(im.filename).with_suffix('.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg')
  File "/Users/jeffhale/miniconda3/envs/hint/lib/python3.9/pathlib.py", line 892, in with_suffix
    raise ValueError("%r has an empty name" % (self,))
ValueError: PosixPath('.') has an empty name

I'm on a Mac running Mojave

package versions:

# Name                    Version                   Build  Channel
aiofiles                  0.6.0                    pypi_0    pypi
anyio                     2.2.0                    pypi_0    pypi
appdirs                   1.4.4                    pypi_0    pypi
appnope                   0.1.2                    pypi_0    pypi
argon2-cffi               20.1.0                   pypi_0    pypi
astroid                   2.5.1                    pypi_0    pypi
async-generator           1.10                     pypi_0    pypi
attrs                     20.3.0                   pypi_0    pypi
autopep8                  1.5.5                    pypi_0    pypi
babel                     2.9.0                    pypi_0    pypi
backcall                  0.2.0                    pypi_0    pypi
black                     20.8b1                   pypi_0    pypi
bleach                    3.3.0                    pypi_0    pypi
ca-certificates           2021.1.19            hecd8cb5_0  
certifi                   2020.12.5        py39hecd8cb5_0  
cffi                      1.14.5                   pypi_0    pypi
chardet                   4.0.0                    pypi_0    pypi
click                     7.1.2                    pypi_0    pypi
cycler                    0.10.0                   pypi_0    pypi
decorator                 4.4.2                    pypi_0    pypi
defusedxml                0.6.0                    pypi_0    pypi
entrypoints               0.3                      pypi_0    pypi
fastapi                   0.63.0                   pypi_0    pypi
flake8                    3.8.4                    pypi_0    pypi
h11                       0.12.0                   pypi_0    pypi
idna                      2.10                     pypi_0    pypi
ipykernel                 5.5.0                    pypi_0    pypi
ipython                   7.21.0                   pypi_0    pypi
ipython-genutils          0.2.0                    pypi_0    pypi
ipywidgets                7.6.3                    pypi_0    pypi
isort                     5.7.0                    pypi_0    pypi
jedi                      0.17.2                   pypi_0    pypi
jinja2                    2.11.3                   pypi_0    pypi
joblib                    1.0.1                    pypi_0    pypi
json5                     0.9.5                    pypi_0    pypi
jsonschema                3.2.0                    pypi_0    pypi
jupyter-client            6.1.11                   pypi_0    pypi
jupyter-core              4.7.1                    pypi_0    pypi
jupyter-packaging         0.7.12                   pypi_0    pypi
jupyter-server            1.4.1                    pypi_0    pypi
jupyterlab                3.0.9                    pypi_0    pypi
jupyterlab-pygments       0.1.2                    pypi_0    pypi
jupyterlab-server         2.3.0                    pypi_0    pypi
jupyterlab-widgets        1.0.0                    pypi_0    pypi
kiwisolver                1.3.1                    pypi_0    pypi
lazy-object-proxy         1.5.2                    pypi_0    pypi
libcxx                    10.0.0                        1  
libedit                   3.1.20191231         h1de35cc_1  
libffi                    3.3                  hb1e8313_2  
markupsafe                1.1.1                    pypi_0    pypi
matplotlib                3.3.4                    pypi_0    pypi
mccabe                    0.6.1                    pypi_0    pypi
mistune                   0.8.4                    pypi_0    pypi
mypy                      0.812                    pypi_0    pypi
mypy-extensions           0.4.3                    pypi_0    pypi
nbclassic                 0.2.6                    pypi_0    pypi
nbclient                  0.5.3                    pypi_0    pypi
nbconvert                 6.0.7                    pypi_0    pypi
nbformat                  5.1.2                    pypi_0    pypi
ncurses                   6.2                  h0a44026_1  
nest-asyncio              1.5.1                    pypi_0    pypi
notebook                  6.2.0                    pypi_0    pypi
numpy                     1.20.1                   pypi_0    pypi
opencv-python             4.5.1.48                 pypi_0    pypi
openssl                   1.1.1j               h9ed2024_0  
packaging                 20.9                     pypi_0    pypi
pandas                    1.2.2                    pypi_0    pypi
pandocfilters             1.4.3                    pypi_0    pypi
parso                     0.7.1                    pypi_0    pypi
pathspec                  0.8.1                    pypi_0    pypi
pexpect                   4.8.0                    pypi_0    pypi
pickleshare               0.7.5                    pypi_0    pypi
pillow                    8.1.2                    pypi_0    pypi
pip                       21.0.1           py39hecd8cb5_0  
plotly                    4.14.3                   pypi_0    pypi
pluggy                    0.13.1                   pypi_0    pypi
prometheus-client         0.9.0                    pypi_0    pypi
prompt-toolkit            3.0.16                   pypi_0    pypi
ptyprocess                0.7.0                    pypi_0    pypi
pycodestyle               2.6.0                    pypi_0    pypi
pycparser                 2.20                     pypi_0    pypi
pydantic                  1.8                      pypi_0    pypi
pydocstyle                5.1.1                    pypi_0    pypi
pyflakes                  2.2.0                    pypi_0    pypi
pygments                  2.8.0                    pypi_0    pypi
pylint                    2.7.2                    pypi_0    pypi
pyngrok                   5.0.3                    pypi_0    pypi
pyparsing                 2.4.7                    pypi_0    pypi
pyrsistent                0.17.3                   pypi_0    pypi
python                    3.9.1                h88f2d9e_2  
python-dateutil           2.8.1                    pypi_0    pypi
python-jsonrpc-server     0.4.0                    pypi_0    pypi
python-language-server    0.36.2                   pypi_0    pypi
python-multipart          0.0.5                    pypi_0    pypi
pytz                      2021.1                   pypi_0    pypi
pyyaml                    5.4.1                    pypi_0    pypi
pyzmq                     22.0.3                   pypi_0    pypi
readline                  8.1                  h9ed2024_0  
regex                     2020.11.13               pypi_0    pypi
requests                  2.25.1                   pypi_0    pypi
retrying                  1.3.3                    pypi_0    pypi
rope                      0.18.0                   pypi_0    pypi
scikit-learn              0.24.1                   pypi_0    pypi
scipy                     1.6.1                    pypi_0    pypi
seaborn                   0.11.1                   pypi_0    pypi
send2trash                1.5.0                    pypi_0    pypi
setuptools                52.0.0           py39hecd8cb5_0  
six                       1.15.0                   pypi_0    pypi
sniffio                   1.2.0                    pypi_0    pypi
snowballstemmer           2.1.0                    pypi_0    pypi
sqlite                    3.33.0               hffcf06c_0  
starlette                 0.13.6                   pypi_0    pypi
terminado                 0.9.2                    pypi_0    pypi
testpath                  0.4.4                    pypi_0    pypi
threadpoolctl             2.1.0                    pypi_0    pypi
tk                        8.6.10               hb0a8c7a_0  
toml                      0.10.2                   pypi_0    pypi
torch                     1.8.0                    pypi_0    pypi
torchvision               0.9.0                    pypi_0    pypi
tornado                   6.1                      pypi_0    pypi
tqdm                      4.59.0                   pypi_0    pypi
traitlets                 5.0.5                    pypi_0    pypi
typed-ast                 1.4.2                    pypi_0    pypi
typing-extensions         3.7.4.3                  pypi_0    pypi
tzdata                    2020f                h52ac0ba_0  
ujson                     4.0.2                    pypi_0    pypi
urllib3                   1.26.3                   pypi_0    pypi
uvicorn                   0.13.4                   pypi_0    pypi
wcwidth                   0.2.5                    pypi_0    pypi
webencodings              0.5.1                    pypi_0    pypi
wheel                     0.36.2             pyhd3eb1b0_0  
widgetsnbextension        3.5.1                    pypi_0    pypi
wrapt                     1.12.1                   pypi_0    pypi
xz                        5.2.5                h1de35cc_0  
yapf                      0.30.0                   pypi_0    pypi
zlib                      1.2.11               h1de35cc_3  

relevant yolov5 code: from common.py line 197 on

        # Pre-process
        n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs])  # number of images, list of images
        shape0, shape1, files = [], [], []  # image and inference shapes, filenames
        for i, im in enumerate(imgs):
            if isinstance(im, str):  # filename or uri
                im, f = Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im), im  # open
                im.filename = f  # for uri
            files.append(Path(im.filename).with_suffix('.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg')
            im = np.array(im)  # to numpy
            if im.shape[0] < 5:  # image in CHW
                im = im.transpose((1, 2, 0))  # reverse dataloader .transpose(2, 0, 1)

Can't open image file on mac

INFO:     ::1:63379 - "GET / HTTP/1.1" 200 OK
INFO:     ::1:64184 - "POST / HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 389, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/applications.py", line 179, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 182, in app
    raw_response = await run_endpoint_function(
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 133, in run_endpoint_function
    return await dependant.call(**values)
  File "/Users/*/Downloads/yolov5-fastapi-demo-main/server.py", line 160, in detect_via_web_form
    plot_one_box(bbox['normalized_box'], img, label=label,
  File "/Users/*/Downloads/yolov5-fastapi-demo-main/server.py", line 85, in plot_one_box
    fnt = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 36, encoding="unic")
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 836, in truetype
    return freetype(font)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 833, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 193, in __init__
    self.font = core.getfont(
OSError: cannot open resource
Exception in ASGI application
Traceback (most recent call last):
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 389, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/applications.py", line 179, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 182, in app
    raw_response = await run_endpoint_function(
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 133, in run_endpoint_function
    return await dependant.call(**values)
  File "/Users/*/Downloads/yolov5-fastapi-demo-main/server.py", line 160, in detect_via_web_form
    plot_one_box(bbox['normalized_box'], img, label=label,
  File "/Users/*/Downloads/yolov5-fastapi-demo-main/server.py", line 85, in plot_one_box
    fnt = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 36, encoding="unic")
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 836, in truetype
    return freetype(font)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 833, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "/Users/*/opt/anaconda3/lib/python3.8/site-packages/PIL/ImageFont.py", line 193, in __init__
    self.font = core.getfont(
OSError: cannot open resource

PIL Fonts Question

@WelkinU nice work on the demo! I noticed that the PIL font you use looks better than the OpenCV fonts used by yolov5/detect.py, but you mention that they are difficult to scale correctly and may have compatibility issues:

if label:
#drawing text in PIL is much harder than OpenCV due to needing ImageFont class
#for some reason PIL doesn't have a default font that scales...
try:
#works on Windows
fnt = ImageFont.truetype("arial.ttf", 36)
except:
'''
linux might have issues with the above font, so adding this section to handle it
this method is untested. based on:
https://stackoverflow.com/questions/24085996/how-i-can-load-a-font-file-with-pil-imagefont-truetype-without-specifying-the-ab
'''
fnt = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 36, encoding="unic")
txt_width, txt_height = fnt.getsize(label)
draw.rectangle([xyxy[0],xyxy[1]-txt_height-2, xyxy[0]+txt_width+2, xyxy[1]], fill = color)
draw.text((xyxy[0],xyxy[1]-txt_height), label, fill=(255,255,255), font = fnt)

I was thinking of replacing the cv2 labels with PIL labels in yolov5/detect.py (and also adding box labels in pytorch hub results.show() and .save() methods) and wondered if you had any suggestions on the topic from your work here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.