Raspberry Pi 備忘録 / Mbedもあるよ!

Raspberry Pi であれこれやった事の記録

Raspberry pi でロボットアームを動かす その8 別マシンから動画ストリームを使う

ロボットアームを制御している(直結してある)ラズパイ以外で、映像を取得したい。

どうやったら簡単に実現できるか。

Opencv 2.4.8 でやる

別のubuntu マシンの Python プログラムからロボットアームの映像を取得してみる。

まず、入っている opencv のバージョンを確認してみる。

$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'2.4.8'

2.4.8 だ。

API を確認する。

Reading and Writing Images and Video — OpenCV 2.4.8.0 documentation

Python: cv2.VideoCapture() → Python: cv2.VideoCapture(filename) → Python: cv2.VideoCapture(device) → Python: cv.CaptureFromCAM(index) → CvCapture Python: cv.CaptureFromFile(filename) → CvCapture

Parameters: filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, …) device – id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.

ということで、ダイレクトにURLを指定はでき無さそう。

ということで、2種類の書き方を探せた。

Opencv 2.4.8 ストリームで、終了記号を探す方法?
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import cv2 
import urllib 
import numpy as np

stream=urllib.urlopen('http://192.168.100.86:8080/?action=stream')
bytes=''
while True:
    bytes+=stream.read(16384)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a!=-1 and b!=-1:
        jpg = bytes[a:b+2]
        bytes= bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i',i)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            exit(0) 
Opencv 2.4.8 画像を取得し続ける方法
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import base64
import time
import urllib2

import cv2
import numpy as np

req = urllib2.Request('http://192.168.100.86:8080/?action=snapshot');
while True:
        response = urllib2.urlopen(req)
        img_array = np.asarray(bytearray(response.read()), dtype=np.uint8)
        frame = cv2.imdecode(img_array, 1)

        cv2.imshow('frame', frame)
        if cv2.waitKey(30) & 0xFF == ord('q'):
                break

opencv 3.2

APIがことなる。

OpenCV: cv::VideoCapture Class Reference

§ VideoCapture() [2/4]
cv::VideoCapture::VideoCapture  (   const String &  filename    )   
Open video file or a capturing device or a IP video stream for video capturing.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Same as VideoCapture(const String& filename, int apiPreference) but using default Capture API backends

とのことで、いかにも直接 URL を指定できそうだ。

※未確認※