使用 Python 将图像从 Raspberry Pi 写入 ThingSpeak
此示例展示如何使用 Python 将图像从 Raspberry Pi™ 板写入 ThingSpeak® 图像通道。
此示例使用 Raspberry Pi 从相机捕获图像并在本地写入文件。然后,每次拍摄新图像时,图像文件就会发送到 ThingSpeak。您可以将此示例用于连接到网络摄像头或 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()
写入图像
在监视页面视图中的图像显示小组件的同时运行代码。
