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.
Related
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']:
I am programing a QR authentication pdf printing system using flask.
So I get a problem with that.
In hear I compare the generate QR code with the user input Qr code.
If both matches do the print function vise versa.
After generating the QR code it shows on the webpage. Then the user can get a photo and it should show it to the raspberry pi camera. Then it decodes the QR code using OpenCV and sends it back to the flask server.
this is my code up to now
python file
#app.route('/', methods=['GET', 'POST'])
def index():
global qr_cv # get from raspberry pi
global qrdata # generate from flask
if flask.request.method == 'GET':
return flask.render_template("index.html")
if flask.request.method == 'POST':
if qrdata != qr_cv:
return flask.render_template("oops.html")
if (qrdata == qr_cv):
# Print Function
return flask.render_template("printed.html")
return flask.render_template("index.html")
HTML file
<form method=post enctype=multipart/form-data">
<input type=file name=file">
<input type=submit value=Print">
</form>
So my question is when I press the Print button flask should search for the certain time for the qr_cv data because the user had to get a photo of the QR code and go to the raspberry pi camera and show it to it. After showing it will send the data to the flask server.
This code suddenly renders the oops.html file because initially qr_cv send nothing.
So, I need any help from you and I highly appreciate your suggestions.
Thank you!
I am creating an application where I have to read images from a POST call in Flask. I am using the instructions as provided in this question for setting Postman. My Flask code looks like follows:
from flask import Flask, request, session
import cv2
# Initialize the Flask application
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
def predict():
r = request
# convert string of image data to uint8
# decode image
imagefile = request.files.get('imagefile', '')
imagefile.save('temp.jpg')
img = cv2.imread('temp.jpg')
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
return ("SUCCESS")
if __name__ == '__main__':
app.run(debug=True, port=5000)
The program runs fine on calling it for the first time and displays the image correctly, but when I try to call it again without rerunning the python code it gets stuck on sending request. Please let me know what I am doing wrong and how to correct it. I am using Ubuntu 18.04 with the Postman application for Linux.
EDIT
As suggested by #MaxTryk I tried adding breakpoints to find the culprit and it is the image showing section.
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
However, I still don't have any ideas why these statements are causing the second request to hang, so if you know any way to correct it please let me know.
If rerunning the python code solves the issue, the problem must be the code, not Postman - I'd suggest to debug by placing breakpoints to see where the execution hangs up.
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 :)
this is a two-part question: I have seen individual pieces discussed, but can't seem to get the recommended suggestions to work together. I want to create a web service to store images and their metadata passed from a caller and run a test call from Postman to make sure it is working. So to pass an image (Drew16.jpg) to the web service via Postman, it appears I need something like this:
For the web service, I have some python/flask code to read the request (one of many variations I have tried):
from flask import Flask, jsonify, request, render_template
from flask_restful import Resource, Api, reqparse
...
def post(self, name):
request_data = request.get_json()
userId = request_data['UserId']
type = request_data['ImageType']
image = request.files['Image']
Had no problem with the data portion and straight JSON but adding the image has been a bugger. Where am I going wrong on my Postman config? What is the actual set of Python commands for reading the metadata and the file from the post? TIA
Pardon the almost blog post. I am posting this because while you can find partial answers in various places, I haven't run across a complete post anywhere, which would have saved me a ton of time. The problem is you need both sides to the story in order to verify either.
So I want to send a request using Postman to a Python/Flask web service. It has to have an image along with some metadata.
Here are the settings for Postman (URL, Headers):
And Body:
Now on to the web service. Here is a bare bones service which will take the request, print the metadata and save the file:
from flask import Flask, request
app = Flask(__name__)
# POST - just get the image and metadata
#app.route('/RequestImageWithMetadata', methods=['POST'])
def post():
request_data = request.form['some_text']
print(request_data)
imagefile = request.files.get('imagefile', '')
imagefile.save('D:/temp/test_image.jpg')
return "OK", 200
app.run(port=5000)
Enjoy!
Make sure `request.files['Image'] contains the image you are sending and follow http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ to save the file to your file system. Something like
file = request.files['Image']
file.save('./test_image.jpg')
might do what you want, while you will have to work out the details of how the file should be named and where it should be placed.