基於tornado實現web camera

來源:互聯網
上載者:User

標籤:基於   run   hid   list   request   開發   erro   return   comm   

基於tornado實現web camera

近期在學習python。找了一個架構學習,我選擇的是tornado。由於其不僅僅是一個web開發架構,其還是一個server,非同步事件庫,一舉多得。
我一直在完opencv,我想接合他們兩個做一個web camera,這就開始。


在tornado中要實現對一個URL的響應,須要實現你自己的Handle。依據你對外提供的介面。實現相關的介面就好了。


以下為整個project的檔案內容:

import tornado.ioloopimport tornado.webimport tornado.genimport cv2from tornado.options import define,  optionsdefine("port", default = 5000, help = "run in tornado on xxxx port", type = int)define("id", default = 0, help = "camera id", type = int)def auth(func):    def _auth(self):        if not self.current_user:            re = {"code" : 404, "message" : "login failed!"}            self.write(re)        else:            func(self)    return _auth;class BaseHandler(tornado.web.RequestHandler):    def get_current_user(self):        return self.get_secure_cookie("user")class LoginHandler(BaseHandler):    def get(self):        self.write(‘<html><body><form action="/login" method="post">‘                   ‘Name: <input type="text" name="name">‘                   ‘<input type="submit" value="Sign in">‘                   ‘</form></body></html>‘)    def post(self):        name = self.get_argument("name", "error")        if name == "error":            re = {"code" : 404, "message" : "login failed!"}        else:            self.set_secure_cookie("user", name)            re = {"code" : 200, "message" : "login successfully!"}        self.write(re)class CameraHandler(BaseHandler):    @auth    def get(self):        ret, image = self.application.cap.read()    if ret:            self.set_header("Content-Type", "image/jpeg")            self.set_header("Refresh", "1")         self.set_header("content-transfer-encoding", "binary")            r, i = cv2.imencode(‘.jpg‘, image)        if r:                self.write(bytes(i.data))            else:                selt.write(‘Sorry, encode faily!‘)        else:        self.write(‘Sorry, get camera data faily!‘)class Application(tornado.web.Application):    def __init__(self, camera_id):        handlers = [(‘/camera‘, CameraHandler), (‘/login‘, LoginHandler)]        self.cap = cv2.VideoCapture(camera_id)        self.camera_id = camera_id;        tornado.web.Application.__init__(self, handlers, debug = True ,cookie_secret = "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o")    def __del__(self):        self.cap.release()if __name__ == ‘__main__‘:    tornado.options.parse_command_line();    app = Application(options.id)    app.listen(options.port)    tornado.ioloop.IOLoop.instance().start()

這當中還包含了一個login的範例。我學習tornado是為了使用其做app後台,所以我實現了自己的auth的修飾器,這樣僅僅是返回一串json字元。而不是重新導向到login頁面。
在Application構造時設定裝置,在http://localhost:xxx/camera這個url上使用get方法就會返回一副圖片。

    def get(self):        ret, image = self.application.cap.read()    if ret:            self.set_header("Content-Type", "image/jpeg")            self.set_header("Refresh", "1")         self.set_header("content-transfer-encoding", "binary")            r, i = cv2.imencode(‘.jpg‘, image)        if r:                self.write(bytes(i.data))            else:                selt.write(‘Sorry, encode faily!‘)        else:        self.write(‘Sorry, get camera data faily!‘)

這段代碼就是這個功能,開始的時候我僅僅是將資料拿出來就發送,沒有進行imencode。導致瀏覽器不能正確的顯示。使用Refresh實現自己主動的重新整理。
項目地址:https://git.oschina.net/zhouX/web_camera.git

無圖無真相:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemh4NjA0NA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="此處輸入圖片的描寫敘述" title="">

基於tornado實現web camera

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.