Python和烧瓶实时更新心电图图

问题描述 投票:0回答:1

我做了一个简单的Python应用程序烧瓶与用于训练的紧急服务训练模拟器进行交互。在这个应用程序,我想显示的心电图波形和命脉。我能做到这一点使用chartjs,但它是非常缓慢的,因此不适合我的需要。我做了一个使用烧瓶socketio的波形数据点定期喂到我的JavaScript线程类。在socketio事件来更新图表的JavaScript函数被调用。我是新来的所有这些技术,如果我做错了什么和穿线或滥用socketio或可能chartjs或烧瓶真的不是我想知道什么,我应该使用,以实现自己的目标。请告诉我如何提高我的海图更新的性能,这样我就可以显示一个典型的心电波形,像你这样的心电图机在医院看到,在我的浏览器应用程序。

app9.py(主应用程序):

from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, 
copy_current_request_context, Markup
from random import random
from time import sleep
from threading import Thread, Event
import pylab
import scipy.signal as signal
import numpy as np
from itertools import cycle
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()


class ECGThread(Thread):
    def __init__(self):
        self.delay = 1
        super(ECGThread, self).__init__()

    def waveformGenerator(self):
        #infinite loop of pqrst
        print("Generating waveform")
        i=0
        pqrst = signal.wavelets.daub(10)
        pqrst_list = pqrst.tolist()
        while not thread_stop_event.isSet():
            for i in cycle(pqrst_list):
                data=i
                socketio.emit('ecg-update', {'data': data})
                #print('emitted: ' + str(data))
            sleep(self.delay)

    def run(self):
        self.waveformGenerator()


@app.route('/')
def index():
#only by sending this page first will the client be connected to the 
socketio instance
    return render_template('index9.html')

@socketio.on('connect')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the waveform generator thread only if the thread has not been 
    started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = ECGThread()
        thread.start()

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app,debug=True, host='0.0.0.0')

main9.js(用于处理ECG图表的JavaScript):

// function to add data to a chart
function addData(chart, label, data){
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
    });
    chart.update();
}

// function to remove data to a chart
function removeData(chart){
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update()
}


// ECG Chart
var ecgChart = document.getElementById("ecgChart");

    var ecgChart = new Chart(ecgChart, {
        type: 'line',
        data: {
            labels:["1","2","3","4","5","6","7","8","9","10"],
            datasets: [
            {
                label: "My First Dataset",
                fill: false,
                lineTension: 0.1,
                backgroundColor: "rgba(75,192,192,0.4)",
                borderColor: "rgba(75,192,192,1)",
                borderCapStyle: 'butt',
                borderDash: [],
                borderDashOffset: 0.0,
                borderJoinStyle: 'miter',
                pointBorderColor: "rgba(75,192,192,1)",
                pointBackgroundColor: "#fff",
                pointBorderWidth: 1,
                pointHoverRadius: 5,
                pointHoverBackgroundColor: "rgba(75,192,192,1)",
                pointHoverBorderColor: "rgba(220,220,220,1)",
                pointBorderWidth: 2,
                pointRadius: 1,
                pointHitRadius: 10,
                data: [0.18817680007769047, 0.527201188931723, 
                       0.6884590394536007, 0.2811723436605783, 
                      -0.24984642432731163, -0.19594627437737416, 
                       0.1273693403357969, 0.09305736460357118, 
                      -0.0713941471663973,-0.02945753682187802]
            }]
        }
    });

// connect to the socket server.
var socket = io.connect('http://' + document.domain + ':' + 
location.port);

// receive details from server
socket.on('ecg-update', function(msg) {
    number = msg.data
    console.log(msg.data);
    addData(ecgChart,'new data', msg.data);
    removeData(ecgChart);
});

index9.html(HTML):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>{{ title }}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-
        scale=1">
        <script src="http://code.jquery.com/jquery-2.1.1.min.js">
        </script>
        <link rel="stylesheet" href="/static/normalize.css">
        <link rel="stylesheet" href="/static/main.css">

        <script type="text/javascript" 
        src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
        </script>
        <script type="text/javascript" 
src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js">
        </script>
        <script type="text/javascript" src="{{ url_for('static', 
filename='modernizr-3.6.0.min.js') }}"></script>

    </head>
    <body>
        <canvas id="ecgChart" width="600" height="400"></canvas>
        <script type="text/javascript" src="{{ url_for('static', filename='main9.js') }}"></script>
    </body>
</html>
javascript python html chart.js
1个回答
1
投票

我无法用chart.js之得到我想要的结果,但是我发现了两个方法来创建直播心电图图形。

1)smoothiecharts - http://smoothiecharts.org/ - 非常好,简单的制作流媒体直播图表但是没有我需要实现我理想的效果customizeability。

2)http://theblogofpeterchen.blogspot.com/2015/02/html5-high-performance-real-time.html - 我发现了一个博客,有人做现场心电图不使用任何的图表库,而不是他们写有自己的构造,使用requestAnimationFrame(),使其工作进行现场图。这是我用什么。现在我只需要学习如何改变心脏率哈哈。

© www.soinside.com 2019 - 2024. All rights reserved.