LoginSignup
2
3

More than 3 years have passed since last update.

Python3で家庭用ネットワークカメラからJpeg画像をダウンロードしPILで表示する

Posted at

はじめに

Python3で家庭用のネットワークカメラからJPEG画像をダウンロードして、そのまま保存しないでPILで表示するためのメモ。
IO DATAのQwatchシリーズのカメラはAPIの仕様がメーカーからダウンロードでき、JPEG画像をHTTPで取得することが可能。
今回ダウンロードしたカメラの画像をどこかに保存するのではなく、すぐに画像処理に使いたいのでダウンロードしてPIL形式で受けるようにしてみた。

環境

Python 3.7.4
カメラ:TS-NA220W (IO Data)

sample.py
#!/usr/bin/env python
# coding: utf-8

# カメラの設定
IMG_URL = "http://192.168.XXX.XXX:XXXXX/snapshot.jpg"
USER = "YOUR NAME"
PASS = "YOUR PASSWORD"

import io
import base64
import requests
from PIL import Image

# JPEGをダウンロードしPIL形式で返す
def download_pil_image(url, user, pwd):
    # BASIC認証用のヘッダを作成
    userpass = base64.encodebytes(('%s:%s' % (user, pwd)).encode("utf-8"))[:-1]
    headers = {"Authorization": "Basic %s" % userpass.decode("utf-8")}

    # 引数のURLにアクセスしデータをダウンロード
    res = requests.get(url, headers=headers)

    # PIL形式に変換
    img_bin = io.BytesIO(res.content)
    pil_img = Image.open(img_bin)

    return pil_img

# 呼び出し部分
try:
    # カメラ画像を読み込む
    img = download_pil_image(IMG_URL, USER, PASS)
    img.show()
except Exception as e:
        print(e)
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3