LoginSignup
2
1

Webカメラから取得した画像を(ファイル保存なしで)Discord webhookで投稿

Last updated at Posted at 2024-03-31

概要

Webカメラから取得したフレーム画像をJPG形式にエンコードし、POSTデータに含める。
OpenCV-pythonを使用する例では、いったん画像ファイルとして保存し、再度そのファイルを開いてPOSTするサンプルしか見つからなかった。ここに全部メモリ上で実施する方法を、個人的備忘録として記載する。

インストール

適当なLinux機(ラズパイ)でインストールしたときの例。

sudo apt-get install libopencv-dev
sudo apt-get install python3-opencv
pip install opencv-python

実装

下記サンプルを使用するときに必要なimport。

import json
import cv2
import numpy
import requests

Webカメラでキャプチャ

dev/0が対象のWebカメラとする。カメラから撮影したframeを取得する。

cap = cv2.VideoCapture(0)
ret, frame = cap.read()
if ret is False:
    raise Exception("cap.read failed")

画像エンコード

JPEGにエンコードする。

quality = 60 # JPG画像の品質 0~100、60ぐらいで十分かな
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
result, encoded_image = cv2.imencode(".jpg", frame, encode_param)
if not result:
    raise Exception("EncodeError")

JPEGへ圧縮されたbyteデータがNumPy配列(ndarray)で返ってくるので、bytes型へ。

encoded_image_byte = encoded_image.tobytes()

WebhookへPOST

名前file.jpgを適当に指定しPOSTする。POST先はDiscordアプリ等から取得したDiscordサーバー/チャンネルのWebhook URLを指定する(タイトル: Webhooksへの序章 – Discordを参照のこと)。

files = {"attachment": ("file.jpg", encoded_image_byte)}
params = {
    "payload_json": json.dumps(
        {
            "username": "Webhook Test BOT",
            "content": "画像を添付しました。",
            "tts": False,
        }
    )
}
response = requests.post(
    url="https://discord.com/api/webhooks/000000/xxxxxx...", # 「Discordサーバー/チャンネルのWebhook URL」を設定
    data=params,
    files=files,
    headers={},
    timeout=30.0,
)
response.raise_for_status()
webhook_res = response.json()
print(webhook_res) # 結果確認

WebhookへPOST時、デバッグしたいとき

下記をimport直後等に追加することで、詳細なデータが標準出力に流れるようになる。

import http
http.client.HTTPConnection.debuglevel = 1

画像を保存したくなったときは

bytes型をそのまま書き込めば良い。

with open("file.jpg", "wb") as binary_file:
    binary_file.write(encoded_image_byte)
2
1
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
1