使用 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()
写下图像
运行代码,同时监视页面视图中的图像显示小组件。