Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

BottleでArUcoマーカーを追跡し四隅情報をコンソールに出す

前回の成果を活かして、Arucoを追跡する

実際のところ

ハード

camera.py

フレームの出力をバイト列ではなく、imencodeのままで実施。
今回はArUcoのマーカー追跡を使うため、画像として渡さないといけないため。

import cv2

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)
        self.video.set(cv2.CAP_PROP_FPS, 1)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH,  480)
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)
        self.quality = 25
        self.encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), self.quality]

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', image, self.encode_param)

        return jpeg

main.py

ArUcoの判定用メソッドを追加。

from bottle import route, run, response
from bottle import TEMPLATE_PATH, jinja2_template as template

from camera import VideoCamera
import time

import cv2

TEMPLATE_PATH.append("./templates/")

aruco = cv2.aruco
dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)


@route('/')
def index():
    return template('index.html')

def detectArUco(img):
        buf = cv2.imdecode(img, -1)
        corners, ids, rejectedImgPoints = aruco.detectMarkers( buf, dictionary )
        if corners:
           print(corners)


def generateJpeg(camera):
    while True:
        time.sleep(0.2)
        frame = camera.get_frame()
        detectArUco(frame)
        yield (b'--frame\r\n' + b'Content-Type: image/jpeg\r\n\r\n' + frame.tobytes() + b'\r\n\r\n')


@route('/video_feed')
def video_feed():
    response.content_type = 'multipart/x-mixed-replace; boundary=frame'
    return generateJpeg(VideoCamera())

if __name__ == '__main__':
    run(host='0.0.0.0', port=8080)

templates/index.html

<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="/video_feed">
  </body>
</html>