Raspberry Pi[54] 監視カメラの映像をラズパイで取り込む

我が家には数台の監視カメラがあり、スマホの専用アプリで映像を見ることができます。

motion でとれた映像

ただ、録画はSDカードにしか保存されないため、不審者がカメラごと持ち去ってしまえば、それ以上は何もできなくなってしまいます。カメラにはクラウド保存のオプションもありますが、有料サービスです。そこで、ラズパイで Motion を動かし、宅内のラズパイに映像を記録する仕組みを作ろうと考えています。ラズパイのストレージ容量は限られていますが、必要に応じてNASに接続したり、外付けSSDを追加したりすることも可能です。ただ、私はすでに さくらインターネットにサーバーを持っているので、そこに定期的に映像をアップロードする方法が現実的かなと思っています。我が家の監視カメラはすべてRTSPに対応しており、以下のような形式のRTSP URLでアクセスできます。いつかこういう仕組みを作ろうと思っていたので、カメラを選ぶ際にRTSP対応は必須条件にしていました。まずは、motion から。

rtsp://user_name:password@IP_Address192.168.1.30:PORT_NUMBER/live/ch0

motion をインストール

sudo apt update
sudo apt install motion

Motion 設定ファイルの編集
Motion の設定ファイルを編集して、必要な設定を行います。

設定ファイルは /etc/motion/motion.conf です。

motion は共通設定を motion.conf で行い、カメラごとの設定は 個別に行い、motion.conf に読み込みファイルを記述します。修正した箇所のみ以下に書いておきます。その他はいじっていません。


# Start in daemon (background) mode and release terminal. サービスで動かすときは on です。
daemon on

# Target directory for pictures, snapshots and movies 映像を保存するフォルダです。
target_dir /home/pi/motion

############################################################
# Image Processing configuration parameters
############################################################

# Image width in pixels. これは、カメラ個別の設定で上書きされます。 まあ、みんなそうだと思いますが。
width 640

# Image height in pixels.
height 480

# Maximum number of frames to be captured per second.
framerate 15

# Text to be overlayed in the lower left corner of images
text_left CAMERA1

# Text to be overlayed in the lower right corner of images.
text_right %Y-%m-%d\n%T-%q

############################################################
# Motion detection configuration parameters
############################################################

# Always save pictures and movies even if there was no motion. 基本トリガで動くので、デバッグのために強制トリガさせるモードです。
emulate_motion off

# Threshold for number of changed pixels that triggers motion.
threshold 1500

# Noise threshold for the motion detection.
; noise_level 32

# Despeckle the image using (E/e)rode or (D/d)ilate or (l)abel.
despeckle_filter EedDl

# Number of images that must contain motion to trigger an event. トリガ検出してから最低記録するフレーム数
minimum_motion_frames 3

# Gap in seconds of no motion detected that triggers the end of an event. トリガ続けてきた場合のギャップフレーム数
event_gap 60

# The number of pre-captured (buffered) pictures from before motion.
pre_capture 3

# Number of frames to capture after motion is no longer detected. トリが来てからどれくらい記録するか
post_capture 30


############################################################
# Movie output configuration parameters
############################################################

# Create movies of motion events. 動画を記録するので、on 
movie_output on

# Maximum length of movie in seconds. 最大記録フレーム数
movie_max_time 60

# The encoding quality of the movie. (0=use bitrate. 1=worst quality, 100=best)
movie_quality 45

# Container/Codec to used for the movie. See motion_guide.html
movie_codec mp4

# File name(without extension) for movies relative to target directory
movie_filename %t-%v-%Y%m%d%H%M%S

############################################################
# Webcontrol configuration parameters
############################################################

# Port number used for the webcontrol.
webcontrol_port 8080

# Restrict webcontrol connections to the localhost.
webcontrol_localhost on

# Type of configuration options to allow via the webcontrol.
webcontrol_parms 0

############################################################
# Live stream configuration parameters
############################################################

# The port number for the live stream.
stream_port 8081

# Restrict stream connections to the localhost.
stream_localhost off

##############################################################
# Camera config files - One for each camera. カメラ個別の設定ファイル ; を取る。
##############################################################
camera /etc/motion/camera1.conf
; camera /usr/etc/motion/camera2.conf
; camera /usr/etc/motion/camera3.conf
; camera /usr/etc/motion/camera4.conf

##############################################################
# Directory to read '.conf' files for cameras.
##############################################################
; camera_dir /usr/etc/motion/conf.d

カメラ個別の設定

 /usr/etc/motion/camera1.conf
#
# This config file was generated by motion 4.5.1

###########################################################
# Configuration options specific to camera 1
############################################################
# User defined name for the camera.
camera_name CatHouse

# Numeric identifier for the camera.
camera_id 101

# The full URL of the network camera stream.
netcam_url rtsp://mack0113:tomcat0113@192.168.1.30:554/live/ch0

# Image width in pixels.
width 1920

# Image height in pixels.
height 1080

# Text to be overlayed in the lower left corner of images
text_left CAMERA 1

# File name(without extension) for movies relative to target directory
movie_filename CAM01_%t-%v-%Y%m%d%H%M%S

ログファイルと保存先ディレクトリの作成・権限設定

motion がログや保存したファイルにアクセスできるように、適切なディレクトリを作成し、pi ユーザーに権限を与えます。

sudo mkdir -p /var/log/motion
sudo mkdir -p /home/pi/motion
sudo chown -R pi:pi /var/log/motion /home/pi/motion
sudo chmod 755 /var/log/motion /home/pi/motion

Motion のサービスファイルを設定
Motion をサービスとして管理するための設定ファイルを作成します。サービスファイルの内容(User=pi を設定して、pi ユーザーで動作させます):

[Unit]
Description=Motion detection video capture daemon
Documentation=man:motion(1)

[Service]
Type=simple
User=pi
ExecStart=/usr/bin/motion

[Install]
WantedBy=multi-user.target

systemd によるサービス管理設定
サービス設定を反映させるために、systemd に再読み込みを行います。

sudo systemctl start motion
sudo systemctl enable motion  # 自動起動設定
sudo systemctl status motion

動作確認
ログファイルが /var/log/motion/motion.log に出力されるか。

保存先ディレクトリ(/home/pi/motion など)に 動画や画像が保存されるか。

動き検出(motion detection)が機能しているか。

起動後すぐに  inactive になるようです。

状態が「inactive (dead)」になる主な理由

  1. daemon モードによるフォーク動作
    motion の設定ファイルで daemon on が指定されると、motion は起動時にバックグラウンドへフォークします。
    この場合、起動プロセスが終了し、systemd からはメインプロセスが終了したとみなされます。
  2. ユニットファイルの設定の不整合
    systemd はサービスの起動動作をユニットファイルで管理しています。
    • 通常、フォアグラウンドで動作するプロセスの場合は Type=simple を使いますが、
    • バックグラウンドにフォークする(daemon 化する)プロセスの場合は、ユニットファイル内に Type=forking の指定が必要となります。
    もし motion のユニットファイルが Type=simple のままだと、motion 自体がバックグラウンドへ移行したタイミングで systemd はそのプロセスが終了したと判断してしまい、「inactive (dead)」と表示されます。
  3. そこで、/lib/systemd/system/motion.service を以下のように修正します。直接記載ではなく、override ファイルでやるほうがいい良いようですが。
[Unit]
Description=Motion detection video capture daemon
Documentation=man:motion(1)
After=network.target

[Service]
Type=forking
User=pi
ExecStart=/usr/bin/motion -c /etc/motion/motion.conf
ExecStop=/usr/bin/killall motion
Restart=on-failure

[Install]
WantedBy=multi-user.target

その後、お決まりの。

sudo systemctl daemon-reload
sudo systemctl restart motion
sudo systemctl status motion

こうなればOK

motion.service - Motion detection video capture daemon
     Loaded: loaded (/lib/systemd/system/motion.service; enabled; preset: enabled)
    Drop-In: /etc/systemd/system/motion.service.d
             笏披楳override.conf
     Active: active (running) since Sun 2025-04-13 09:08:33 JST; 8min ago
       Docs: man:motion(1)
    Process: 2067 ExecStart=/usr/bin/motion -c /etc/motion/motion.conf (code=exited, status=0/SUCCESS)
   Main PID: 2068 (motion)
      Tasks: 8 (limit: 4755)
        CPU: 4min 53.437s
     CGroup: /system.slice/motion.service
             笏披楳2068 /usr/bin/motion -c /etc/motion/motion.conf

サービスで動かない場合は以下のようにすれば良いですが、これまた自動起動をさせると面倒ですのでなるべくサービスで動かしましょう。

sudo motion -c /etc/motion/motion.conf