Showing an image on an HTML page without saving to disk - python

I want to load an image from the folder do some processing on it and then show it on the HTML page without storing on the disk. I followed this post which discusses similar problem but image is not showing
Here is the code I am using
app.py
from flask import Flask, render_template
from base64 import b64encode
import cv2 as cv
import os
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
target = os.path.join(APP_ROOT, 'static')
#app.route("/")
def index():
uri1 = ''
return render_template("output.html", uri1=uri1)
#app.route("/img_prcoess", methods=['POST'])
def img_prcoess():
# Read the image
src_img = cv.imread("/".join([target, 'bradley_cooper.jpg']))
# Convert image to Gray
img1_gray = cv.cvtColor(src_img, cv.COLOR_BGR2GRAY)
# Encode
uri1 = "data:%s;base64,%s" % ("image/jpeg", b64encode(img1_gray))
return render_template("output.html", uri1=uri1)
if __name__ == "__main__":
app.run(port=4444, debug=True)
output.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" action="{{ url_for('img_prcoess') }}" method="POST" enctype="multipart/form-data">
<input type="submit" value="Show Image" id="button1" width="100px">
</form>
<img style="height: 300px" src="{{ uri1 }}">
</body>
Directory Structure

You cannot convert the raw data of the image into a data url. You have to change the format first.
#app.route('/process', methods=['POST'])
def process():
path = os.path.join(APP_ROOT, 'static', 'example.jpg')
srcimg = cv.imread(path)
dstimg = cv.cvtColor(srcimg, cv.COLOR_BGR2GRAY)
retval, buffer = cv.imencode('.jpg', dstimg)
uri = "data:%s;base64,%s" % ('image/jpeg', b64encode(buffer).decode('ascii'))
return render_template('process.html', **locals())

Related

python Unsupported method ('POST')

python Unsupported method ('POST') this program is meant to convert images to text but I kept getting this error over and over I don't know what is the problem
I don't know exactly if the problem with the HTML code or this code
or am I missing other files
I don't quite understand the HTML code so I will be thankful if you elaborate
from gettext import gettext
from click import get_text_stream
from flask import Flask, render_template, request
import os, pytesseract
from jinja2 import Template
from flask_uploads import UploadSet, configure_uploads, IMAGES
from PIL import Image
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__, static_url_path='', static_folder = 'static', template_folder = 'gg.html')
photos = UploadSet('photos', IMAGES)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER'] = 'images'
class UploadText(object):
def __init__(self, file):
self_file = pytesseract.image_to_string(Image.open(project_dir + '/imges/' + file))
#app.route('/gg', methods =["POST" , "GET"])
def home():
if request.method == "POST":
if 'photo' not in request.files:
return 'there is no photo in form'
name = request.form['img-name'] + '.jpg'
photo = request.files['photo']
path = os.path.join(app.config['UPLOAD_FOLDER'], name)
photo.save(path)
textObject = get_text_stream(name)
return textObject.file
return render_template('gg.html')
if __name__ == ' __main__':
app.run()
The HTML:
<head>
<meta charset = "utf-8">
<title> Image to Text</title>
</head>
<body>
<div class='text-center'><br><br>
<form method='post' enctype="multipart/form-data">
<input type="file" class='btn btn-dark' name='photo'>
<input id ='input' type='text' class ='form-control' placeholder='enter image name' name='img-name'>
<input class = 'btn btn-dark' type='submit'>
</form>
</div>
</body>
<style>
#input{
margin: auto;
width: auto;
}
</style>
You don't specify an action attribute in the HTML <form> tag, which tells the form where to submit to. Instead try:
<form method='post' action='/gg' enctype="multipart/form-data">
Of course it's also possible to render the /gg part dynamically, based on the name of your python function home:
<form method='post' action='{{ url_for("home") }}' enctype="multipart/form-data">

Having Problems for Redirecting pages in Flask

I have a code which consists of app.py, template folder(index and results).
I am using dropzone to upload my images/videos.
I am facing problems during uploading the images/videos. After i upload it the page doesn't go on results.html to show the uploaded images. Instead it stays on the same page. But the image/video is saved in my directory.
Please have a look through.
app.py:
import os
from flask import Flask, render_template, request, session, redirect, url_for
from flask_dropzone import Dropzone
from flask_uploads import UploadSet
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config.update(
UPLOADED_PATH=os.path.join(basedir, 'uploads'),
# Flask-Dropzone config:
DROPZONE_MAX_FILE_SIZE=1024, # set max size limit to a large number, here is 1024 MB
DROPZONE_TIMEOUT=5 * 60 * 1000 # set upload timeout to a large number, here is 5 minutes
)
app.config['SECRET_KEY'] = 'supersecretkeygoeshere'
app.config['DROPZONE_REDIRECT_VIEW'] = 'results'
dropzone = Dropzone(app)
#app.route('/', methods=['POST', 'GET'])
def index():
#set session for image results
if "filename" not in session:
session['filename'] = []
#list to hold our uploaded image urls
filename = session['filename']
#handle image upload from dropzone
if request.method == 'POST':
f = request.files.get('file')
f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
#append image urls
filename.append(filename.url(filename))
session['filename'] = filename
return "uploading..."
return render_template('index.html')
#app.route('/results')
def results():
#redirect to home if no images to display
if "filename" not in session or session['filename'] == []:
return redirect(url_for('index'))
#set the filename and remove the session variables
filename = session['filename']
session.pop('filename', None)
return render_template('results.html', filename=filename)
if __name__ == '__main__':
app.run(debug=True)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask-Dropzone Demo</title>
{{ dropzone.load_css() }}
{{ dropzone.style('border: 2px dashed #0087F7; margin: 10%; min-height: 400px;') }}
</head>
<body>
{{ dropzone.create(action='index') }}
{{ dropzone.load_js() }}
{{ dropzone.config() }}
</body>
</html> ```
results.html:
<html><h1>These are your uploaded images</h1>
Back<p>
<ul>
{% for filenm in filename %}
<li><img style="height: 150px" src="{{ filenm }}"></li>
{% endfor %}
</ul>
</p> </html>

TypeError: 'JpegImageFile' object is not callable

I'm actually trying to link my ml model(inception) with flask . The
output is binary (0 or 1). The image format is jpg or jpeg (both). I have tried with .stream while asking for input. Actually the model doesnt take image when file = Image.open(request.files['file'].stream).
flask code :
import os
from try1 import obj12
from flask import Flask, request, render_template,
send_from_directory,send_file
from PIL import Image
import io
import cv2
app = Flask(__name__)
#app.route("/")
def index():
return render_template('test.html')
#app.route("/upload", methods=['GET','POST'])
def upload():
file = request.files['file']
image = Image.open(file)
count = obj2(image)
print (count)
return (count)
if __name__ == "__main__":
#port = int(os.environ.get('PORT', 5000))
app.run(debug=True)
html code :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST"
enctype="multipart/form-data">
<strong>Files:</strong><br>
<input id="file-picker" type="file" name="file" accept="image/*"
multiple>
<div id="msg"></div>
<input type="submit" value="Upload!" id="upload-button">
</form>
</body>
</html>
Just want to pass my image in that model.

Jinja2 Using images in HTML

I wasted a lot of time to find out what is wrong. I need your help now.
I want to render template with image from my filesystem. But it is not working.
Path - string that contains file name
#app.route('/', methods=['GET'])
def main():
return render_template('main.html',image = path)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h2></h2>
<form method="post" enctype="multipart/form-data" action="/uploader">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<img src={{ url_for('static', filename = image) }} >//i can't figure how to change this to use {{image}}
</body>
</html>
Just generate full image path in your view and pass it to your template
#app.route('/', methods=['GET'])
def main():
#path is filename string
image_file = url_for('static', filename=path)
return render_template('main.html', image_file=image_file)
and then just use it as full link
<img src={{ image_file}} >
if you have image file (with filename which stored in path) in your static folder this should work
If you was set the static folder like that (or other methods):
from flask import Flask
app = Flask(__name__, static_folder='static')
#app.route('/', methods=['GET'])
def main():
return render_template('main.html', image = url_for("static", filename=path))
or shorter:
return render_template('main.html', image='/static/' + path))
after you will put your image in /static folder you can get it from template:
<img src="{{image)}}">
I think something like this should work.
<img src="{{ url_for('static', filename='image') }}">
Where 'image' refers to the path of the image file inside static folder. Make sure to use the full name of image file along with its file type i.e. jpg, png etc.

Files not uploading in flask

I am trying to upload files into server using flask but the files are *not uploading.
I am new to python and flask.
import os
from flask import *
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route('/')
def index():
return render_template('upload.html')
#app.route('/upload', methods = ['POST'])
def upload():
target = os.path.join(APP_ROOT, 'uploads/')
if not os.path.join(target):
os.mkdir(target)
for file in request.files.getlist('file'):
print(file.filename)
destination = '/'.join([target, file.filename])
print(destination)
file.save(destination)
return render_template('successful.html')
if __name__ == '__main__':
app.run(debug = True)
upload.html
<!DOCTYPE html>
<html>
<head>
<title> Upload file </title>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}"
method="post" enctype="multipart/form-data">
<input type="file" name="cssv_file" multiple>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Change this line
if not os.path.join(target):
to
if not os.path.isdir(target):

Categories