-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
55 lines (44 loc) · 1.77 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import datetime, io, torch
from PIL import Image
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
DATETIME_FORMAT = "%Y-%m-%d_%H-%M-%S-%f"
@app.route("/", methods=["GET", "POST"])
def home():
global model
if request.method == "POST":
if "file" not in request.files:
return redirect(request.url)
file = request.files["file"]
if not file:
return
img_bytes = file.read()
img = Image.open(io.BytesIO(img_bytes))
results = model([img])
results.render() # updates results.imgs with boxes and labels
now_time = datetime.datetime.now().strftime(DATETIME_FORMAT)
img_savename = f"static/{now_time}.png"
Image.fromarray(results.ims[0]).save(img_savename)
return redirect(img_savename)
return render_template("index.html")
@app.route('/detection', methods=["POST"])
def predict():
global model
if not request.method == "POST":
return
if request.files.get("image"):
image_file = request.files["image"]
image_bytes = image_file.read()
img = Image.open(io.BytesIO(image_bytes))
results = model(img, size=640) # reduce size=320 for faster inference
results.render() # updates results.imgs with boxes and labels
now_time = datetime.datetime.now().strftime(DATETIME_FORMAT)
img_savename = f"static/{now_time}.png"
Image.fromarray(results.ims[0]).save(img_savename)
gambar = {'image': img_savename}
hasil = results.pandas().xyxy[0].to_dict(orient='records')
hasil.insert(0, gambar)
return hasil
if __name__ == "__main__":
model = torch.hub.load('yolov5', 'custom', path='model/model.pt', source='local')
app.run(host='0.0.0.0', port=5000)