.. note::

    こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ！Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。

    **参加する理由は？**

    - **エキスパートサポート**：コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
    - **学び＆共有**：ヒントやチュートリアルを交換してスキルを向上させましょう。
    - **独占的なプレビュー**：新製品の発表や先行プレビューに早期アクセスしましょう。
    - **特別割引**：最新製品の独占割引をお楽しみください。
    - **祭りのプロモーションとギフト**：ギフトや祝日のプロモーションに参加しましょう。

    👉 私たちと一緒に探索し、創造する準備はできていますか？[|link_sf_facebook|]をクリックして今すぐ参加しましょう！

.. _3.1.2_py_pi5:

3.1.2 ビデオモジュール
=========================

はじめに
-----------------

写真撮影に加えて、カメラモジュールを使用してビデオを録画することもできます。

必要な部品
------------------------------

このプロジェクトには、次のコンポーネントが必要です。 

.. image:: ../python_pi5/img/3.3.2_photograph_list.png
  :width: 800

一式を購入するのが便利です、こちらがリンクです： 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - 名前	
        - このキットのアイテム
        - リンク
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

以下のリンクから別々に購入することもできます。

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - コンポーネントの紹介
        - 購入リンク

    *   - :ref:`cpn_camera_module`
        - |link_camera_buy|

実験手順
------------------------------

**ステップ 1:** Raspberry Piデスクトップに入ります。より良い体験のために画面が必要な場合は、 `Connect your Raspberry Pi <https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up/3>`_ を参照してください。または、リモートでRaspberry Piデスクトップにアクセスするには、 :ref:`remote_desktop` の詳細なチュートリアルを参照してください。

**ステップ 2:** ターミナルを開き、コードのフォルダに入ります。

.. code-block::

    cd ~/raphael-kit/python-pi5

**ステップ 3:** 実行します。

.. code-block::

    sudo python3 3.1.2_VideoModule_zero.py

コードを実行して録画を開始します。 ``Ctrl+C`` を押して録画を終了します。ビデオは ``my_video.h264`` という名前で ``~/`` ディレクトリに保存されます。

.. note::

    ``~/raphael-kit/python-pi5`` パスの ``3.1.2_PhotographModule_zero.py`` をPython IDEで開き、実行ボタンをクリックしてコードを実行し、停止ボタンでコードを停止することもできます。

写真をPCに送りたい場合は、 :ref:`filezilla` を参照してください。

.. warning::

    エラー メッセージ ``RuntimeError: Cannot determine SOC peripheral base address`` が表示された場合は、 :ref:`faq_soc` を参照してください。

**コード**

.. code-block:: python

   #!/usr/bin/env python3

   import time
   from picamera2 import Picamera2, Preview
   from picamera2.encoders import H264Encoder
   from picamera2.outputs import FfmpegOutput
   import os

   # Get the current user's login name
   user = os.getlogin()
   # Get the path to the user's home directory
   user_home = os.path.expanduser(f'~{user}')

   # Create a Picamera2 instance
   camera = Picamera2()
   # Retrieve the default preview configuration
   preview_config = camera.preview_configuration

   try:
       # Configure preview size and format
       preview_config.size = (800, 600)
       preview_config.format = 'XRGB8888'
       # Start the camera preview in QTGL mode
       camera.start_preview(Preview.QTGL)

       # Define video configuration with size, frame rate, and buffer count
       conf = {'size': (800, 600)}
       controls = {'FrameRate': 40}
       config = camera.create_video_configuration(main=conf, controls=controls, buffer_count=12)
       # Create a video encoder with a specified bitrate
       encoder = H264Encoder(bitrate=10000000)
       # Define output file for the video
       output = FfmpegOutput(f'{user_home}/my_video.mp4')
       # Configure and start recording
       camera.configure(config)
       camera.start_recording(encoder, output)
       # Record for 10 seconds
       time.sleep(10)
       # Stop the recording
       camera.stop_recording()

   except KeyboardInterrupt:
       # Stop the camera preview if a KeyboardInterrupt (e.g., Ctrl+C) occurs
       camera.stop_preview()
       pass


**コード説明**

#. 必要なライブラリとクラスをインポートします。 ``picamera2`` ライブラリはカメラ制御用、 ``H264Encoder`` はビデオエンコーディング用、 ``FfmpegOutput`` はビデオ出力ファイルを定義するために使用されます。

   .. code-block:: python

       #!/usr/bin/env python3

       import time
       from picamera2 import Picamera2, Preview
       from picamera2.encoders import H264Encoder
       from picamera2.outputs import FfmpegOutput
       import os

#. 現在のユーザーのログイン名とそのホームディレクトリのパスを取得します。

   .. code-block:: python

       # Get the current user's login name
       user = os.getlogin()
       # Get the path to the user's home directory
       user_home = os.path.expanduser(f'~{user}')

#. ``Picamera2`` クラスのインスタンスを作成し、デフォルトのプレビュー設定を取得します。

   .. code-block:: python

       # Create a Picamera2 instance
       camera = Picamera2()
       # Retrieve the default preview configuration
       preview_config = camera.preview_configuration

#. プレビューのサイズとフォーマットを設定します。サイズは800x600ピクセルに設定され、フォーマットは ``XRGB8888`` に設定されます。

   .. code-block:: python

       try:
           # Configure preview size and format
           preview_config.size = (800, 600)
           preview_config.format = 'XRGB8888'

#. QTGLモードでカメラプレビューを開始します。これはグラフィカルなプレビューモードです。

   .. code-block:: python

       try:
           ...          
             
           # Start the camera preview in QTGL mode
           camera.start_preview(Preview.QTGL)
           
           ...

#. ビデオ設定を800x600ピクセルのフレームサイズと、秒間40フレームのフレームレートで定義します。

   .. code-block:: python

       try:
           ...
           
           # Define video configuration with size, frame rate, and buffer count
           conf = {'size': (800, 600)}
           controls = {'FrameRate': 40}
           config = camera.create_video_configuration(main=conf, controls=controls, buffer_count=12)
           
           ...

#. 10Mbpsの指定されたビットレートでH.264エンコーディング形式を使用するビデオエンコーダを作成します。ビデオの出力ファイルパスを設定し、ユーザーのホームディレクトリに ``my_video.mp4`` として保存します。

   .. code-block:: python

       try:
           ...

           # Create a video encoder with a specified bitrate
           encoder = H264Encoder(bitrate=10000000)
           # Define output file for the video
           output = FfmpegOutput(f'{user_home}/my_video.mp4')
           
           ...

#. 定義されたビデオ設定でカメラを設定し、指定されたエンコーダと出力ファイルを使用して録画を開始し、10秒間録画した後、録画を停止します。

   .. code-block:: python

       try:
           ...

           # Configure and start recording
           camera.configure(config)
           camera.start_recording(encoder, output)
           # Record for 10 seconds
           time.sleep(10)
           # Stop the recording
           camera.stop_recording()

#. このコードブロックは、Ctrl+CなどのKeyboardInterruptを処理し、カメラプレビューを停止します。 ``pass`` 文は、例外を処理する際に他の操作を行わないように使用されます。

   .. code-block:: python

       except KeyboardInterrupt:
           # Stop the camera preview if a KeyboardInterrupt (e.g., Ctrl+C) occurs
           camera.stop_preview()
           pass



