I am running my Flask app on Ubuntu VPS (linode) as server. I am capturing image from android studio sending it to flask server to get response. Image is being sent as base64 string from android studio.
But the response is too slow when using request.form.to_dict(). Both ubuntu vps and android app are running on different IP.
I've put timestamps on different processes and found this request.form.to_dict() is the problem taking around 22 to 35 secs.
I am also using image compressing techniques on my android studio code but still too much time.
Tried on gunicorn with nginx but same.
threaded = True
Images are of around 400kb to 500kb size.
Kindly help me to figure out this issue.
Below is my flask code:
#app.route('/predict', methods=['POST', 'GET'])
def predict():
if request.method == 'POST':
file = request.form.to_dict()['upload'] # 22.2491 sec
b64_string = file
image = imread(io.BytesIO(base64.b64decode(b64_string))) #0.0023 sec
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) # 0.000171 sec
.....
.....
.....
sending the images in base64 format is not the recommended method, you should try to send the photo via a multipart request.
Look here to see how to send an image from android in multipart form data (if you are using java).
If you send the images via multipart form data you will then be able to access them on flask using the method request.files['my_file_name']:
#app.route('/upload', methods=['POST'])
def upload_file():
my_file = request.files['my_file_name']:
Related
I am new to using raspberry pi's and don't really have any knowledge on flask.
So, I'm trying to implement Github webhooks with a python flask + ngrok to automatically git pull when a new push has been made to the repository. This is so I can just work on my Windows computer, push via Github Desktop and have it automatically pull the code from the repository using webhooks (the url from ngrok) to my raspberry's local repository. I use flask and ngrok to receive the webhook, which when received, starts pulling from the repo.
The issue is that the code for receiving the webhook doesn't work on my raspberry pi. The code below works perfectly fine on my Windows pc and works as expected, but when use the exact same code on my raspberry pi it just doesn't receive the webhook nor print anything. I don't really know what's going on, should work as expected.
from flask import Flask, request, json
import subprocess
app = Flask(__name__)
#app.route('/')
def root():
return 'Working'
# This receives the webhooks and does code when received
#app.route('/', methods=['POST'])
def webhook():
print("Receiving data...")
data = json.loads(request.data)
print ("\n\nNew commit by: {}".format(data['commits'][0]['author']['name'])) # Inform that someone has committed
print("\n\nPulling repository...")
subprocess.run(["git", "pull"]) # Pull new code from repo
print("Finished pulling.\nLocal repository up-to-date!\n\n")
return "OK"
if __name__ == '__main__':
app.run(debug=True)
I have a problem. I'm making a Flask application that requires camera input, which is sent to opencv, and then I process it and return an image. I have no problem with the streaing. My issue here is the fact that I need to access the user's webcam, and give the information to Flask so it can process the image, and THEN return it. To do this, I need access to the user's webcam. I imagine something like this:
main.py
from flask import Flask, request, render_template
from myapp import process #Import function to process image
app = Flask(__name__)
#app.route("/webcam", methods=["GET", "POST"])
def camera():
if request.method == "POST":
image = request.get_json()['image']
result = process(image) #Process image
return result
else:
return('camera.html') #Return camera site
#Other code/functions...
Then in the html file, I'd have a <script> tag with the script to send a post request with the image.
(If there is a better way to do this, tell me.)
I don't know how to get the image to the user, though, in a way that OpenCV can process it.
i need to get image from url(request.args.get) and upload the same image to server using python Flask.
from flask import *
app = Flask(__name__)
#app.route('/success')
def success():
IMAGE= request.args.get('image')
image=cv2.imread(IMAGE)
ksize=(12,10)
image = cv2.blur(image, ksize)
cv2.imwrite(r"C:\Users\SiddanthShaiva\Desktop\ss_flask.jpg",image)
return "successfull"
app.run()
Till now, api/flask is running only if the image is present in my system ,if image is provided from other system it is not working, how to make api to run when image is loaded through any system?
N: The same api is hosted in the server, but requires image to be present in server and it is throwing error when image is not there in server.
So how to make this api working when image is given from any system?Please help, thanks :)
You can post the image: requests_post_files
client:
import requests
requests.post(url, files={'image': open('image.jpg', 'rb')})
server:
from flast import request
binary_image = request.files['image'].read()
with open('image.jpg', 'wb') as fid:
fid.write(binary_image)
I am trying to make an API that when a POST request is made, it will accept images and then save them, and if a GET request is made then it will send back a URL to where you'd be able to download that image. How would that be possible?
This is the Flask app running on localhost for testing:
from flask import Flask, send_file
app = Flask(__name__)
#app.route("/upload_image/<filename>", methods=["POST"])
def upload_image(filename):
# receive the image here
# ...
#app.route("/get_image", methods=["GET"])
def get_image():
filename = "encoded_image.png"
return send_file(filename, mimetype="image/png")
if __name__ == "__main__":
app.run(host="localhost", port=5000)
I think sending the image is easy but I don't know how to go about receiving it and using requests to send it.
This is the idea behind the main code:
import requests
option = input()
if option == "get image":
print("Download the image at: https://localhost:5000/get_image")
elif option == "upload image":
post = requests.post("https://localhost:5000/upload_image/encoded_image.png")
i don't want the images to change names. I always want to send the file encoded_image.png and receive it, because I want it to be overwritten when the POST is made. This is for a discord bot but that doesn't really affect anything, I just thought I'd mention it. Thanks in advance :)
I am using docker for a data-science project. The docker image contains a python code that reads a file(image file), processes it, and generates a vector of floats as an output.
I am using flask micro-framework for a user to interact with the container. Here is the server-side code (running inside the container). It is of course buggy!
from flask import Flask, request
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
#app.route('/process_image', methods=['GET', 'POST'])
def process_image():
params = request.json
with open(params["file_name"]. "r") as f:
# the above access to a file in host machine from docker container,
# will definetly lead to an access error.
# do some processing
pass
Here is the client-side code
import requests
file_name = "some-path/image.jpg" # on the host machine
requests.get('http://0.0.0.0:5000/process_image/', json={"file_name": file_name})
What is the right way to pass a file via requests to the container? I am looking at a solution where the client-side code is minimal and the user must be able to send a file stored at any location in the host-machine.
I am new to docker as well as web-programming, I would appreciate any feedback/suggestion. Thanks in advance!