LoginSignup
7
9

More than 5 years have passed since last update.

Raspberry Piとカメラを使って、データを書き込まずに画像をPOSTする方法 with OpenCV

Last updated at Posted at 2018-05-20

はじめに

現場でラズパイを使って画像データ収集するにあたり、少しでもmicroSDの寿命を伸ばしたいという願いから、可能な限りmicroSDへの書き込みを減らそうと思い、手順を調べたのでまとめます。

ラズパイに必要なもの

  1. 内蔵用カメラまたはUSBカメラ
  2. Python3
  3. OpenCV

サーバーに必要なもの

  1. HTTPサーバ
  2. Ruby

カメラによる撮影と画像の送信

カメラを取り付けたラズパイで以下のスクリプトを実行。

/home/pi/post.py
#!/usr/bin/env python3

import cv2
import time
import requests

cap = cv2.VideoCapture(0)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

time.sleep(1)
ret, frame = cap.read()

url = "http://xxx.xxx.xxx.xxx/upload.cgi"

files = {'imgData': cv2.imencode('.jpg', frame)[1].tobytes()}
res = requests.post(url, files=files)

cap.release()

画像データの受信

受信するサーバに以下のCGIスクリプトを設置して待機。

upload.cgi
#!/usr/bin/env ruby

require "cgi"

formData = CGI.new

print "Content-type: text/html\n\n"

open("./data.jpg","wb") do |fh|
  fh.binmode
  fh.write formData['imgData'].read
end

puts "OK"

自動実行

カメラを取り付けたラズパイにて以下のコマンドを実行。

chmod a+x post.py

1分おきに自動実行するよう設定。

crontab -e

以下の一行を追加。

*/1 * * * * /home/pi/post.py

できた(^-^)

7
9
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
7
9