Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Constructing Image Classification API with Tensorflow and FastAPI

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Use Tensorflow and FastAPI to build image classification API, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

Let's start with a simple example of helloworld

First, we import the FastAPI class and create an object application. This class has some useful parameters, such as we can pass the title and description of the swaggerui.

From fastapi import FastAPIapp = FastAPI (title='Hello world')

We define a function and use @ app.get. This means that our API/index supports the GET method. The functions defined here are asynchronous, FastAPI automatically handles async and does not use asynchronous methods by creating thread pools for ordinary def functions, and it uses asynchronous event loops for asynchronous functions.

@ app.get ('/ index') async def hello_world (): return "hello world" Image recognition API

We will create an API to classify images, which we will name predict/image. We will use Tensorflow to create an image classification model.

Tensorflow Image Classification course: https://aniketmaurya.ml/blog/tensorflow/deep%20learning/2019/05/12/image-classification-with-tf2.html

We created a function load_model that will return a MobileNet CNN model with pre-training weights, that is, it has been trained to classify 1000 different categories of images.

Import tensorflow as tfdef load_model (): model = tf.keras.applications.MobileNetV2 (weights= "imagenet") print ("Model loaded") return model model = load_model

We define a predict function that accepts the image and returns the prediction. We resize the image to 224x224 and standardize the pixel value to [- 1pd1].

From tensorflow.keras.applications.imagenet_utils import decode_predictions

Decode_predictions is used to decode the class name of the predicted object. Here we will return to the first two possible classes.

Def predict (image: Image.Image): image = np.asarray (image.resize ((224,224) [...,: 3] image = np.expand_dims (image, 0) image = image / 127.5-1.0 result = decode_predictions (model.predict (image), 2) [0] response = [] for I Res in enumerate (result): resp = {} resp ["class"] = res [1] resp ["confidence"] = f "{res [2] * 100pur0.2f}%" response.append (resp) return response

Now we will create an API/predict/image that supports file upload. We will filter the file extension to support only images in jpg, jpeg, and png formats.

We will use Pillow to load the uploaded image.

Def read_imagefile (file)-> Image.Image: image = Image.open (BytesIO (file)) return image @ app.post ("/ predict/image") async def predict_api (file: UploadFile = File (...): extension = file.filename.split (".") [- 1] in ("jpg", "jpeg", "png") if not extension: return "Image must be jpg or png format!" Image = read_imagefile (await file.read ()) prediction = predict (image) return prediction final code import uvicornfrom fastapi import FastAPI, File, UploadFilefrom application.components import predict, read_imagefileapp = FastAPI () @ app.post ("/ predict/image") async def predict_api (file: UploadFile = File (...): extension = file.filename.split (".") [- 1] in ("jpg", "jpeg") "png") if not extension: return "Image must be jpg or png format!" Image = read_imagefile (await file.read ()) prediction = predict (image) return prediction @ app.post ("/ api/covid-symptom-check") def check_risk (symptom: Symptom): return symptom_check.get_risk_level (symptom) if _ _ name__ = = "_ _ main__": does uvicorn.run (app, debug=True) help you after reading the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report