このページは機械翻訳を使用して翻訳されました。最新版の英語を参照するには、ここをクリックします。
PythonでRaspberry PiからThingSpeakに画像を書き込む
この例では、Python を使用して Raspberry Pi™ ボードから ThingSpeak ® 画像チャネルに画像を書き込む方法を示します。
この例では、Raspberry Pi を使用してカメラから画像をキャプチャし、ローカルにファイルを書き込みます。その後、新しい画像が撮影されるたびに、画像ファイルが ThingSpeak に送信されます。提供されたコードで選択された行に応じて、Web カメラまたは Pi カメラに接続された Raspberry Pi にこの例を使用できます。
Pi カメラの場合は、
raspistill
コマンドを使用できます。このコードをウェブカメラで使用するには、fswebcam
を使用します。これは、
sudo apt-get install fswebcam
この例を実行するには、Pi がインターネットにアクセスできる必要があります。
設定
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()
イメージを書き込む
ページ ビューで画像表示ウィジェットを監視しながらコードを実行します。