I am trying to run a python script. I have an input field in html which will pass the values to js file. Then I used python-shell to pass the values in a form of arguments to the python script to execute them. I am using express.js for scripting
Here is my temp.ejs file
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<img src="./my_plot.png">
<form>
<input type="text" id="source" />
<button onclick="get_data();">Go!</button>
</form>
</body>
</html>
Index.js
function get_data() {
var source = document.getElementById("source").value;
alert(source);
var options = {
args: [source],
pythonPath: '/usr/bin/python3'
};
var tests = new PythonShell('hello.py', options);
tests.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
}
python file
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
CHANNELS = 2
swidth = 4
Change_RATE = 2
T = int(sys.argv[1])
#print(source)
q = 0.5
Q = 1/10
A = 1 # amplitude of signal # quatization stepsize
N = 2000
spf = wave.open('sample.wav', 'rb')
RATE=spf.getframerate()
Byte = spf.getsampwidth()
signal = spf.readframes(1024)
signal = np.fromstring(signal, 'Int16')
def uniform_midtread_quantizer(x, Q):
# limiter
x = np.copy(x)
idx = np.where(np.abs(x) >= 1)
x[idx] = np.sign(x[idx])
# linear uniform quantization
xQ = Q * np.floor(x/Q + 1/2)
return xQ
def plot_signals(x, xQ, T):
e = xQ - x
plt.figure(figsize=(10,6))
plt.plot(signal, label=r'quantized signal $x_Q[k]$')
plt.xlabel(r'$k$')
plt.axis([0, N, -T, T])
plt.grid()
plt.savefig('my_plot.png')
# generate signal
x = signal
# quantize signal
xQ = uniform_midtread_quantizer(x, Q)
# plot signals
plot_signals(x, xQ, T)
When I am doing node index.js in terminal then I am getting the desired output but not when I pass the value through html (so no error with python and js file)
Express.js is not causing the error as i have used vanilla ja also but same error occured
Related
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
from PIL import Image
import requests
from io import BytesIO
img_src = 'https://unsplash.it/500/300'
response = requests.get(img_src)
img = Image.open(BytesIO(response.content))
img = np.asarray(img.convert('L'))
fig,ax = plt.subplots()
zlims = (np.percentile(img[:, :], 0), np.percentile(img[:, :], 100 - 0))
im = ax.imshow(img, aspect='auto',vmin=zlims[0], vmax=zlims[1])
threshold = 0.
axthreshold = plt.axes([0.2, 0.01, 0.65, 0.03])
sthreshold = Slider(axthreshold, 'clip', -.1, 15.,
valinit=threshold, valstep=None)
def update(val):
ax.clear()
zlims = (np.percentile(img[:, :], .1+val), np.percentile(img[:, :], 100 - (.1+val)))
print(zlims[0],zlims[1])
ax.imshow(img, aspect='auto',vmin=zlims[0], vmax=zlims[1])
fig.canvas.draw_idle()
sthreshold.on_changed(update)
update(threshold)
this creates a image where you can limit what range the colormap covers with a slider. As "clip" increases the color map variety lessens.
Im am pretty familiar with flask. Is there any way to implement something like this into flask? I would prefer matplotlib but I'm ok with trying anything.
Thanks!
--Update--- I realized that I don't want to refresh the page every time the picture is adjusted. I tried plotly javascript approach. I was happy until I realized the res is too low.
html:
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.plot.ly/plotly-2.11.1.min.js"></script>
<style>
.container {
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="container" id="myDiv"></div>
<div class="container">
<input style="width:50%" id="slide" type="range" min="0" max="5" step="0.025" value=".1" name="name_of_slider">
</div>
<div class="container" id="sliderAmount"></div>
<script>
const z1 = JSON.parse('{{ Lsort | tojson }}');
const IMG = JSON.parse('{{ IMG | tojson }}');
var size = z1.length
var qlower = z1[Math.ceil(size * .1 / 100) - 1]
var qupper = z1[Math.ceil(size * (100-.1) / 100) - 1]
var data = [
{
z: IMG,
type: 'heatmap',
colorscale: 'Viridis',
zauto: false,
zmax: qupper,
zmin: qlower,
}
];
var layout = {
autosize: false,
width: 1000,
height: 600,
};
Plotly.newPlot('myDiv', data, layout);
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
var perc = this.value
var qlower = z1[Math.ceil(size * perc / 100) - 1]
var qupper = z1[Math.ceil(size * (100-perc) / 100) - 1]
var data = [
{
z: IMG,
type: 'heatmap',
colorscale: 'Viridis',
zauto: false,
zmax: qupper,
zmin: qlower,
}
];
var layout = {
autosize: false,
width: 1000,
height: 600,
};
Plotly.newPlot('myDiv', data, layout);
}
</script>
</body>
</html>
python:
from PIL import Image
import requests
from io import BytesIO
img_src = 'https://unsplash.it/500/300'
response = requests.get(img_src)
imgarray = Image.open(BytesIO(response.content))
imgarray = np.asarray(imgarray.convert('L'))
n = np.sort(imgarray.ravel()).tolist()
imgarray2D = np.flip(imgarray,axis=0)
imgarray2D = imgarray2D.tolist()
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def main():
return render_template('clip.html',Lsort = n,IMG=imgarray2D)
if __name__ == '__main__':
app.run()
I am no expert in Flask or Javascript, but I did something (maybe clumsy!) similar to a Matplotlib slider using an HTML range slider.
So, you put one of those sliders (with a class="watch" because you're watching it) and an HTML img in your web-page's HTML so you will have at least a slider in the index.html:
<input name="XXX" id="YYY" style="width:100%" class="watch" type="range" step="1" min="0" max="255" value="0">
and also an img:
<img src="{{url_for('static', filename='default.png')}}" id="image" class="img-fluid">
Then attach an onChange() function to the slider like this so it gets called whenever the slider is moved:
$(document).ready(function() {
$(".watch").on( "change input", fChanged);
fChanged(); // do one initial update before user changes anything
});
You'll also need the jQuery CDN stuff. I used:
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
And the function fChanged() gathers up the values of a number of sliders on the HTML page into a JSON to send to Flask endpoint called /_refresh like this:
{# https://flask.palletsprojects.com/en/2.0.x/patterns/jquery/ #}
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
function fChanged(eObj) {
$.getJSON($SCRIPT_ROOT + '/_refresh', {
Hmin: $('#Hmin').val(),
Hmax: $('#Hmax').val(),
Smin: $('#Smin').val(),
Smax: $('#Smax').val(),
Vmin: $('#Vmin').val(),
Vmax: $('#Vmax').val(),
mask: jQuery("input[type='radio']").filter(":checked").attr("value")
}, function(data) {
$("#code").text(data.code);
$("#image").attr("src", "data:image/png;base64,"+data.image);
});
return false;
}
You can see I had 6 sliders, a min and a max for each of Hue, Saturation and Value.
The Flask endpoint returned another JSON containing some code I wanted to display on the webpage and a base64-encoded PNG-format result image that I then used to update an HTML img by writing its src attribute.
The Python code for the _refresh endpoint looks like this - it does some other stuff with Hue, Saturation and Value that isn't interesting to you, but it shows how I processed the image and encoded it for returning as a JSON to the webpage:
#app.route('/_refresh')
def refresh():
# DEBUG print(request.args)
Hmin = request.args.get('Hmin')
Hmax = request.args.get('Hmax')
Smin = request.args.get('Smin')
Smax = request.args.get('Smax')
Vmin = request.args.get('Vmin')
Vmax = request.args.get('Vmax')
mask = request.args.get('mask')
# Do the image processing
if 'localfilename' in session:
im, HSV = loadImage(session['localfilename'])
else:
im, HSV = loadImage('default')
lo = np.array([Hmin,Smin,Vmin], dtype=np.uint8)
hi = np.array([Hmax,Smax,Vmax], dtype=np.uint8)
mask = cv2.inRange(HSV, lo, hi)
alpha = np.zeros((im.shape[0],im.shape[1]), dtype=np.uint8) + mask
res = np.dstack((im, alpha))
# DEBUG
# cv2.imwrite('result.png', res)
_, PNG = cv2.imencode(".png", res)
b64img = encodebytes(PNG.tobytes()).decode('ascii')
response = {
'Status' : 'Success',
'image': b64img,
: 'code': render_template('code.py', Hmin=Hmin, Hmax=Hmax, Smin=Smin, Smax=Smax, Vmin=Vmin, Vmax=Vmax)
}
return jsonify(response) # send the result to client
You are not obliged to use OpenCV for the processing or base64-encoding, you can equally do all that with PIL/Pillow if you prefer - just ask, or look at any of my previous PIL/Pillow answers.
It might all be clumsy and misguided but it worked for me. I'll be glad too if someone else shows a better way!
By the way, if anyone is using macOS and trying to run the code in your question, the GUI with the image and slider pops up briefly and disappears. You can then spend ages reading about Matplotlib backends, how to list them, how to see what's available, how to change them, that you need a "framework" Python installation, or maybe don't and after around an hour, you discover that all you need is to add an extra line as follows:
...
ax.imshow(img, aspect='auto',vmin=zlims[0], vmax=zlims[1])
fig.canvas.draw_idle()
plt.show() # add this line if plot flashes and disappears
I am working on Yolov3, OpenCV,python and Flask. Here, I explain the details of usage for each item.
Yolov3 - To detect and recognize object in video input
Opencv - To capture images of detected object in video input.
Flask - As a web server since it's support python language.
My objective
To develop application which able to captured the image of the object and update in the flask web directly or real-time
For your information, currently my system able to capture image and save in one folder which name as images by using OpenCv and python. you can refer the code below.
opencv and python code to capture image of object detected
for i in range(len(boxes)):
if i in indexes:
x,y,w,h = boxes[i]
label = str(LABELS[class_ids[i]])
confidence= confidences[i]
color = colors[class_ids[i]]
crop_img = image[y:y + h, x:x + w]
imagesPath = "images/file_%d.jpg"%self.d
cv2.imwrite(imagesPath, crop_img)
self.d+=1
cv2.rectangle(image,(x,y),(x+w,y+h),color,2)
cv2.putText(image,label+" "+str(round(confidence,2)),(x,y+30),font,1,(255,255,255),2)
When the images successfully save in images folder. I convert all the images in to base64 and return as json in flask. Here I attach the python code in flask.
Covert image to base64 and render in html templates
#app.route("/images")
def get_images():
directory = os.listdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
os.chdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
image_list= list()
for file in directory:
data = dict()
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
image_list.append(data)
final_data = {'files':image_list}
return render_template('images.html', final_data=final_data)
images.html
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>yolo</title>
</head>
<body>
<h1 class="logo">Results</h1>
<ul>
{% for data in final_data.files %}
<li>{{data.label}}</li>
<img alt="embedded" src="data:image/jpg;base64,{{data.data}}"/>
{% endfor %}
</ul>
</body>
</html>
Problem and question
I have two major problem here.
1) When i run my application, my application captured the images welly. But it's automatically stop when image.html page is open to display the picture. Why it's happen and how to solve this?
2) If the application able to capture image even i open the image.html page. What should i do to update my web directly or real-time?
Here I attach the full code. Because I have been works for many weeks but still not found the solution. Hope someone can helps. Let's me know if u need more information
code
App.py
from flask import Flask, render_template, Response,jsonify
from camera import VideoCamera
import numpy as np
import os
import time
import detect as dt
from PIL import Image
import cv2
import base64
import json
from pprint import pprint
app = Flask(__name__)
def success_handle(output, status=200, mimetype='application/json'):
return Response(output, status=status, mimetype=mimetype)
#app.route("/images")
def get_images():
directory = os.listdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
os.chdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
flist = list()
for file in directory:
data = dict()
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
flist.append(data)
final_data = {'files':flist}
return render_template('images.html', final_data=final_data)
#app.route('/')
def index():
return render_template('index.html')
def gen(camera):
frame_id = 0
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
camera.py
import cv2
import time
import os
import numpy as np
font = cv2.FONT_HERSHEY_PLAIN
starting_time= time.time()
frame_id = 0
count = 0
d = 0
labelsPath = os.path.sep.join(["yolo-coco", "coco.names"])
weightsPath = os.path.sep.join(["yolo-coco", "yolov3.weights"])
configPath = os.path.sep.join(["yolo-coco", "yolov3.cfg"])
#imagesPath = 'C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images/file_%d.jpg"%d'
labelsPath = os.path.sep.join(["yolo-coco", "coco.names"])
VideoPath = os.path.sep.join(["videos", "highway.mp4"])
LABELS = open(labelsPath).read().strip().split("\n")
net = cv2.dnn.readNet(configPath, weightsPath)
layer_names = net.getLayerNames()
outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors= np.random.uniform(0,255,size=(len(LABELS),3))
class VideoCamera(object):
def __init__(self):
# Using OpenCV to capture from device 0. If you have trouble capturing
# from a webcam, comment the line below out and use a video file
# instead.
self.video = cv2.VideoCapture(VideoPath)
self.frame_id = 0
self.d = 0
# If you decide to use video.mp4, you must have this file in the folder
# as the main.py.
# self.video = cv2.VideoCapture('video.mp4')
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream.
self.frame_id+=1
#print(frame_id)
height,width,channels = image.shape
#print (frame.shape)
#detecting objects
blob = cv2.dnn.blobFromImage(image,0.00392,(320,320),(0,0,0),True,crop=False) #reduce 416 to 320
net.setInput(blob)
outs = net.forward(outputlayers)
#print(outs)
print(outs[1])
#Showing info on screen/ get confidence score of algorithm in detecting an object in blob
class_ids=[]
confidences=[]
boxes=[]
for out in outs:
#print(out)
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
print(confidence)
if confidence > 0.8:
#object detected
center_x= int(detection[0]*width)
center_y= int(detection[1]*height)
w = int(detection[2]*width)
h = int(detection[3]*height)
#cv2.circle(img,(center_x,center_y),10,(0,255,0),2)
#rectangle co-ordinaters
x=int(center_x - w/2)
y=int(center_y - h/2)
#cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
boxes.append([x,y,w,h]) #put all rectangle areas
confidences.append(float(confidence)) #how confidence was that object detected and show that percentage
class_ids.append(class_id) #name of the object tha was detected
indexes = cv2.dnn.NMSBoxes(boxes,confidences,0.4,0.6)
# result = open('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images/frame%04d.txt'%(count), 'w')
for i in range(len(boxes)):
if i in indexes:
x,y,w,h = boxes[i]
label = str(LABELS[class_ids[i]])
# cv2.imwrite(label, crop_img)
confidence= confidences[i]
color = colors[class_ids[i]]
crop_img = image[y:y + h, x:x + w]
imagesPath = "images/file_%d.jpg"%self.d
cv2.imwrite(imagesPath, crop_img)
self.d+=1
cv2.rectangle(image,(x,y),(x+w,y+h),color,2)
cv2.putText(image,label+" "+str(round(confidence,2)),(x,y+30),font,1,(255,255,255),2)
elapsed_time = time.time() - starting_time
fps=frame_id/elapsed_time
cv2.putText(image,"FPS:"+str(round(fps,2)),(10,50),font,2,(0,0,0),1)
# cv2.imshow("Image",image)
# key = cv2.waitKey(1) #wait 1ms the loop will start again and we will process the next frame
# if key == 27: #esc key stops the process
# break;
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
index.html
<html>
<head>
<title>Object Detection</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>
images.html
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>yolo</title>
</head>
<body>
<h1 class="logo">Results</h1>
<ul>
{% for data in final_data.files %}
<li>{{data.label}}</li>
<img alt="embedded" src="data:image/jpg;base64,{{data.data}}"/>
{% endfor %}
</ul>
</body>
</html>
I am trying to import https://github.com/tkurki/dnssd.js and make html file like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
<script src="/index.js"></script>
</head>
<body>
<section>
<h1>DNS-SD Browser</h1>
<div id="services"></div>
</section>
<script>
const dnssd = require('dnssd2');
// advertise a http server on port 4321
const ad = new dnssd2.Advertisement(dnssd.tcp('http'), 4321);
ad.start();
// find all chromecasts
const browser = dnssd2.Browser(dnssd.tcp('_http'))
.on('serviceUp', service => console.log("Device up: ", service))
.on('serviceDown', service => console.log("Device down: ", service))
.start();
</script>
</body>
</html>
But somehow it shows me error in console log:
Uncaught ReferenceError: require is not defined at index.js:1
Uncaught ReferenceError: require is not defined at index.js:18
What am I doing wrong please?
index.js contains:
var Advertisement = require('./lib/Advertisement');
var Browser = require('./lib/Browser');
var ServiceType = require('./lib/ServiceType');
var validate = require('./lib/validate');
var resolve = require('./lib/resolve');
var NetworkInterface = require('./lib/NetworkInterface');
module.exports = {
Advertisement: Advertisement,
Browser: Browser,
ServiceType: ServiceType,
tcp: ServiceType.tcp,
udp: ServiceType.udp,
all: ServiceType.all,
validate: validate,
resolve: resolve.resolve,
resolveA: resolve.resolveA,
resolveAAAA: resolve.resolveAAAA,
resolveSRV: resolve.resolveSRV,
resolveTXT: resolve.resolveTXT,
resolveService: resolve.resolveService,
};
The browser doesn't support require function
Use requirejs. You can also use it with jquery
You can learn about requirejs from here
Browser doesn't support require out-of-box. try adding this script tag to manually import require from its cdn.
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="/index.js"></script>
I'm currently using Apache Thrift for an API project.
I started with a little test project in order to understand how Thrift works. So, I would like to use a python server with a browser-based javascript Client.
I've read the documentation entirely, but I still have an issue I can't resolve :( :
Server output :
127.0.0.1 - - [04/Dec/2018 17:04:34] code 501, message Unsupported method ('OPTIONS')
127.0.0.1 - - [04/Dec/2018 17:04:34] "OPTIONS / HTTP/1.1" 501 -
test.thrift
enum Modulation
{
BPSK
QPSK
APSK16
APSK32
}
struct Coordinate {
1: i32 X,
2: i32 Y
}
struct Constellation {
1: string name,
2: i32 timestamp,
3: list<Coordinate> coordinates
}
service Dealer
{
Constellation getConstellation()
Modulation getModulation()
void setModulation(1: Modulation new_modulation)
i32 getTimestamp()
}
server.py
import glob
import sys
sys.path.append('gen-py')
from TApp import Dealer
from TApp.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import *
from thrift.server import TServer, THttpServer
import time
class DealerHandler:
def __init__(self):
self.modulation = Modulation.BPSK
def getConstellation(self):
c = Constellation()
c.name = "Test"
c.timestamp = self.getTimestamp()
c.coordinates = []
return c
def getModulation(self):
return self.modulation
def setModulation(self, new_modulation):
self.modulation = new_modulation
def getTimestamp(self):
return int(str(time.time()).split('.')[0])
if __name__ == '__main__':
handler = DealerHandler()
processor = Dealer.Processor(handler)
port = 9090
host = '127.0.0.1'
# HTTP SERVER
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TJSONProtocol.TJSONProtocolFactory()
# List of all protocols : https://thrift-tutorial.readthedocs.io/en/latest/thrift-stack.html
#server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server = THttpServer.THttpServer(processor, (host, port), pfactory)
server.serve()
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div id="timestamp" style="margin:auto; width:70%; padding:15px; text-align:center; border:1px solid black;">
No Value
</div>
<br />
<button type="button" name="button" class="btn btn-info" style="width:100%" onclick="update_timestamp()">Start connection</button>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" charset="utf-8"></script>
<script src="thrift.js" charset="utf-8"></script>
<script src="test_types.js" charset="utf-8"></script>
<script src="Dealer.js" charset="utf-8"></script>
<script type="text/javascript">
function update_timestamp() {
var transport = new Thrift.TXHRTransport("http://localhost:9090");
var protocol = new Thrift.TJSONProtocol(transport);
var client = new DealerClient(protocol);
var val = client.getTimestamp();
document.getElementById("timestamp").innerHTML = val;
}
</script>
</html>
I'm developing a web application in linux environnement to display image of data array.
So i would like to save images from python plot to jpeg files to be able to display them in a browser. Python code works correctly when executed from the console. But if called with a javascript request it hangs due to plt use, even with pltioff(). done message is send if i remove all plt code.
python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import os
import json
curr = os.getcwd()
plt.ioff()
fig, ax = plt.subplots( 1 )
ax.plot([1, 2, 3])
plt.show()
fig.savefig(curr+"/"+'test.jpeg',dpi=224,quality=50)
messJ = json.dumps( "done" )
print('Content-type: text/html')
print("\n")
print "%s" %messJ
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my page</title>
</head>
<body >
<input type="button" id="plotsrv" value="plotsrv" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="pythonplot.js"></script>
javascript :
document.getElementById('plotsrv').addEventListener('click', trait_Vdatasrv, false);
function trait_Vdatasrv (e) {
var url = 'pyplot.py';
console.log("url:"+url);
$.post(url,{ file:'ncfile' }, function(data){
$('#data').html(data);
console.log("data"+data);
var jsdec=JSON.parse(data);
console.log(jsdec); }
); }
Regards
I finally found ,
it is needed to add matplotlib.use('Agg')
to avoid display output