forked from cyrildiagne/basnet-http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
78 lines (61 loc) · 1.93 KB
/
main.py
File metadata and controls
78 lines (61 loc) · 1.93 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import io
import os
import sys
from flask import Flask, request, send_file, jsonify
from flask_cors import CORS
from PIL import Image
import numpy as np
import time
import logging
import tempfile
import random
import string
import basnet
logging.basicConfig(level=logging.INFO)
# Initialize the Flask application
app = Flask(__name__)
CORS(app)
# Simple probe.
@app.route('/', methods=['GET'])
def hello():
return 'Hello BASNet!'
# Route http posts to this method
@app.route('/', methods=['POST'])
def run():
start = time.time()
# Convert string of image data to uint8
if 'data' not in request.files:
return jsonify({'error': 'missing file param `data`'}), 400
data = request.files['data'].read()
if len(data) == 0:
return jsonify({'error': 'empty image'}), 400
# Convert string data to PIL Image
img = Image.open(io.BytesIO(data))
# Resize image to 256 (BASNet compliant), and crop it
img.thumbnail((256, 256))
box = (0, 0, 256, 256)
cropped_image = img.crop(box)
# Process Image
res = basnet.run(np.array(cropped_image))
# Create mask file, load it in memory and remove file
maskfilename = randomString(8) + ".png"
res.save(maskfilename)
mask = Image.open(maskfilename).convert("L")
os.remove(maskfilename)
empty = Image.new("RGBA", cropped_image.size, 0)
newImg = Image.composite(cropped_image, empty, mask)
# Save to buffer
buff = io.BytesIO()
newImg.save(buff, 'PNG')
buff.seek(0)
# Print stats
logging.info(f'Completed in {time.time() - start:.2f}s')
# Return data
return send_file(buff, mimetype='image/png')
def randomString(stringLength=8):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
if __name__ == '__main__':
os.environ['FLASK_ENV'] = 'development'
port = int(os.environ.get('PORT', 8080))
app.run(debug=True, host='0.0.0.0', port=port)