Main Content

このページは機械翻訳を使用して翻訳されました。元の英語を参照するには、ここをクリックします。

Python を使用して Raspberry Pi からThingSpeakに画像を書き込む

この例では、Python を使用して Raspberry Pi™ ボードからThingSpeak® 画像チャネルに画像を書き込む方法を示します。

この例では、Raspberry Pi を使用してカメラから画像をキャプチャし、ローカルにファイルを書き込みます。その後、新しい画像が撮影されるたびに、画像ファイルがThingSpeakに送信されます。提供されたコードで選択された行に応じて、Web カメラまたは Pi カメラに接続された Raspberry Pi にこの例を使用できます。

Pi カメラの場合は、 raspistill コマンドを使用できます。このコードをウェブカメラで使用するには、 fswebcamを使用します。これは、次のコマンドを使用して取得できます。

sudo apt-get install fswebcam

このサンプルを実行するには、Pi がインターネットにアクセスできる必要があります。

python-image-ex.jpg

設定

1) 画像チャネルを作成するの説明に従って、新しいThingSpeakイメージチャネルを作成します。

2) 新しいチャネルでデータの収集の説明に従って、新しいThingSpeakデータチャネルを作成します。

3) イメージの表示の説明に従って、画像表示ウィジェットをデータチャネルのビューに追加します。

コード

1) Python コードに次のライブラリを含めます。

#!/usr/bin/python

from time import sleep
import os
import requests
import sys

2) Thingspeakチャネル、資格情報、および画像ファイルの場所を指定する変数を定義します。

# Update this section with your ThingSpeak Image Channel ID and Image Channel API Key
thingspeakImageChannelID = 'YOUR_THINGSPEAK_IMAGE_CHANNEL_ID'
thingSpeakImageChannelAPIKey = 'YOUR_THINGSPEAK_IMAGE_CHANNEL_API_KEY'
localFileName = '/home/pi/snapshot.jpg'
thingSpeakURL = 'https://data.thingspeak.com/channels/' + thingspeakImageChannelID + '/images'

3) Raspberry Pi カメラボードからスナップショットを保存します。

def getSnapshotBytes():
   # Use FSWEBCAM to save a screenshot from a webcam. This requires the FSWEBCAM package.
   # Use raspistill to save a screenshot from a Pi Cam.
   # Alternatively, you can use OpenCV to directly get the bytestream from the camera.
   imageByteStream = None
   returnCode = os.system('fswebcam -r 1024x768 -S 1 -q ' + localFileName) # Use this line for webcam.
   # returnCode = os.system(‘raspistill -o ‘ + localFileName) # Use this line for a pi cam.
   if returnCode == 0:
      fh = open(localFileName, 'rb')
      imageByteStream = fh.read()
      fh.close()
   return imageByteStream

4) ループを実行してスナップショットをキャプチャし、それをThingSpeakイメージチャネルに書き込みます。

def main():
   # Loop infinitely
   while True:
      # Get image bytes
      imData = getSnapshotBytes()
      # POST image to ThingSpeak if there is a valid image
      if imData is not None:
         x = requests.post(url = thingSpeakURL, data = imData,
             headers = {'Content-Type': 'image/jpeg',
             'thingspeak-image-channel-api-key': thingSpeakImageChannelAPIKey,
             'Content-Length' : str(sys.getsizeof(imData))})
         print(x)
         # Sleep so we do not get locked out of ThingSpeak for posting too fast
         sleep(30)

if __name__=="__main__":
   main()

画像を書き込む

ページ ビューで画像表示ウィジェットを監視しながらコードを実行します。

stapler_image_widget.jpg