使用树莓派摄像头识别二维码,并通过http返回结果

树莓派接上摄像头后运行此程序,在本机电脑访问树莓派启动的web端口,可直接获取二维码扫描的结果,或者获取当前摄像头照片。

由于树莓派自带python版本是2.7,本文使用python2,python3需少量修改。

使用的库

大部分使用pip直接安装即可,具体安装方法自行搜索

  • picamera
  • flask
  • zbar
  • PIL

获取摄像头图像

下面的程序可获取当前摄像头的图像

import picamera.array
from PIL import Image

with picamera.PiCamera() as camera:
    camera.resolution = (1366, 768)
    camera.framerate = 10
    print "start preview direct from GPU"
    camera.start_preview()
    with io.BytesIO() as stream:
        camera.capture(stream, 'jpeg')
        im = Image.open(stream)

with picamera.PiCamera() as camera:打开了摄像头,这时候我们只要我们只要在这个with层级下,摄像头就不会关闭,可以一直获取图像。
而怎么让运行的时候一直保持在此层级下呢,没错答案就是让程序阻塞在此。当然不能用while True:实现阻塞,我们还要运行flask框架,我们知道flask在运行的时候是阻塞的,所以可以利用这个,让程序阻塞。

结合flask通过http返回结果

import picamera.array
import io
import base64
from cStringIO import StringIO
from PIL import Image
from flask import Flask, jsonify
import zbar

print "create app..."
app = Flask(__name__)

with picamera.PiCamera() as camera:
    camera.resolution = (1366, 768)
    camera.framerate = 10
    print "start preview direct from GPU"
    camera.start_preview()


    @app.route('/')
    def hello():
        return "hello"


    @app.route('/image')
    def get_img():
        print "---------", "start get img"
        with io.BytesIO() as stream:
            camera.capture(stream, 'jpeg')
            print "capture"
            im = Image.open(stream)
            output_buffer = StringIO()
            im.save(output_buffer, format='JPEG')
            binary_data = output_buffer.getvalue()
            base64_data = base64.b64encode(binary_data)
            print "base64:"
            return "<img width='100%' src=\"data:image/jpg;base64," + base64_data + "\">"


    @app.route('/qr')
    def get_qr():
        with io.BytesIO() as stream:
            camera.capture(stream, 'jpeg')
            im = Image.open(stream)
            # im = Image.open("Z.jpg")
            pil = im.convert('L')
            width, height = pil.size
            raw = pil.tobytes()
            image = zbar.Image(width, height, 'Y800', raw)
            scanner = zbar.ImageScanner()
            scanner.parse_config('enable')
            scanner.scan(image)
            res = []
            for symbol in image:
                print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
                res.append({
                    "type": str(symbol.type),
                    "data": symbol.data
                })
            return jsonify({
                "status": 0,
                "data": res
            })


    app.run(host="0.0.0.0", port=8080, threaded=True)
阅读更多
个人分类: 树莓派
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭