ラズパイ4 カーネル5.1.0(2021.5.7版 32bitおすすめ全部入り)を使用しています
GUIの設定からカメラを使用するにしておく。(要再起動)
フィルムケーブルでカメラと本体(ラズパイ4)をつなぐ。USB端子の反対側に銀色の端子面が来るようにフィルムケーブルを接続。
レガシーな4種類のコマンド(raspistill, raspivid、raspiyuv 、 raspividyuv)と新しいlibcameraコマンドは同時に使えない。後述する/boot/config.txtを書き換えが必用。
追加情報202208 以下の情報があり、前提条件がだいぶ異なってしまうようです。
2021年11月にリリースされたRaspberry Pi OS Bullseye (バージョン2021-10-30)において、カメラ制御がlibcameraに変更になりました。
https://www.indoorcorgielec.com/resources/raspberry-pi/camera-setup/#Raspberry_Pi_OS%E3%81%AE%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6
ラズパイのインターフェース設定画面でも「カメラを有効にする」オプションが無くなっており、カメラを接続するだけで利用できるようです。
libcamera-still -t 20000 とすれば20秒プレビューを表示します。
動作テスト コマンドライン(レガシーコマンド)
sudo raspistill -o image.jpg とターミナル(端末)から実行。
プレビューが動作していなければ、参考HPによりカメラ認識、アップデートを確認する。https://www.pc-koubou.jp/magazine/17276
sudo raspistill -t 10000 -o image.jpg プレビュー時間を10秒にする。
-vf オプションで上下反転 公式案内https://www.raspberrypi.org/documentation/usage/camera/raspicam/raspistill.md
オプション(help)はこちら
--ss オプションでシャッター速度(μs)を設定できる。ただし、isoは同時に設定できず、1/60秒以下でiso400に固定、長時間側ではiso自動設定のよう。
--ev オプションで1/6EVステップの補正。--ev 6 で1EVのプラス補正。
利用可能なコマンド(レガシーコマンド)
公式によるとレガシーな4種類のコマンド、静止画用のraspistill, raspivid、動画用のraspiyuv 、 raspividyuv がある。
https://www.raspberrypi.org/documentation/raspbian/applications/camera.md
さらに、新しいアプローチとしてlibcameraが紹介されている。
https://www.raspberrypi.org/documentation/hardware/camera/README.md
libcameraはここでも紹介されているが、新しいアプローチとしてこちらを使うべきなのだろうか?https://soho-enterprise.com/2020/08/04/post-792/
新しい libcamera を試してみる(ラズパイ3の場合は公式サイト熟読のこと)
https://www.raspberrypi.org/documentation/linux/software/libcamera/README.md
公式に従い、インストールをすすめる。今回ラズパイ4なので設定が少ない。ラズパイ3だと追加の設定がいくつかある。
/boot/config.txtを書き換える。管理者権限が必要なので、ターミナルから
sudo mousepad config.txtでエディターを立ち上げる。
dtoverlay=imx219 を最後に追加。今回のカメラの素子はソニーimx219。保存後再起動。
注:再起動後、カメラシステムの制御はARMコアに渡され、ファームウェアベースのカメラ機能(raspistillなど)は機能しなくなります。と記載があるので、必要に応じ設定を戻す。
libcameraとqcamの準備
sudo apt install libboost-dev
sudo apt install libgnutls28-dev openssl libtiff5-dev
sudo apt install qtbase5-dev libqt5core5a libqt5gui5 libqt5widgets5
sudo apt install meson
sudo pip3 install pyyaml ply
sudo pip3 install --upgrade meson で先ほど入れたmesonを新しくする。
ラズパイ4ならそのまま次のコマンドへ
git clone git://linuxtv.org/libcamera.git
cd libcamera
meson build
cd build
meson configure -Dpipelines=raspberrypi -Dtest=false
cd ..
ninja -C build
sudo ninja -C build install
build/src/qcam/qcam を実行 ここでやっとカメラ画像の確認ができる
Raspberry Pi's libcamera-appsの準備
cd (ホームディレクトリに戻る)
sudo apt install libegl1-mesa-dev
git clone https://github.com/anholt/libepoxy.git
cd libepoxy
mkdir _build
cd _build
meson
ninja
sudo ninja install
さらに、
cd
sudo apt install cmake libboost-program-options-dev libdrm-dev libexif-dev
git clone https://github.com/raspberrypi/libcamera-apps.git
cd libcamera-apps
mkdir build
cd build
cmake ..
make -j4
./libcamera-hello
libcamera-apps/build/libcamera-hello
で動作確認。エラーが発生したので再起動して同じディレクトリ(build)まで降りてきてから再度実行して、映像を確認できました。ちょっと手数がおおいですが、クリーンな環境だからかうまく行きました。
libcamera-hello --help でヘルプを表示
libcamera-hello --vflip で上下反転
libcameraのヘルプ
さらなるlibcameraの説明はこちらhttps://github.com/raspberrypi/libcamera-apps/blob/main/README.md
##libcameraのpythonコード
先ほどのインストールでlibcamera-appsの下に test.py が作成されている。これをこの場所で実行すると一通り動作確認(機能紹介)してくれる。
libcamera-apps下のbuildフォルダに作成された実行ファイル libcamera-jpegなどを実行する。撮影した写真はbuildフォルダに作成されるが、テスト前後で消去される。(拡張子だけを見て削除しているので注意)
test.pyを編集して中核部分のみにしたのが以下。このコードをtest.pyに貼付。別のpyファイルから
import testとして
test.test_my_jpeg(dir,shutter_sp)で実行可能。 dirは実行ファイルがあるbuildフォルダ shutter_spはシャッター速度usec。
上下反転とシャッター速(引数)を追加。
def test_my_jpeg(dir,shutter_sp):
executable = os.path.join(dir, 'libcamera-jpeg')
output_jpg = os.path.join(dir, 'test.jpg')
output_shutter = os.path.join(dir, 'shutter.jpg')
logfile = os.path.join(dir, 'log.txt')
# "jpg test". See if the executable appears to run and write an jpg output file.
print(" jpg test")
retcode, time_taken = run_executable([executable, '-t', '1000', '-o', output_jpg,'--vflip'],
logfile)
retcode, time_taken = run_executable(
[executable, '-t', '1000', '-o', output_shutter,'--vflip',
'--shutter', str(shutter_sp), '--gain', '1.0'], logfile)
raspstillその他のオプション
-q, --quality : Set jpeg quality <0 to 100>
-r, --raw : Add raw bayer data to jpeg metadata
-l, --latest : Link latest complete image to filename
-t, --timeout : Time (in ms) before takes picture and shuts down (if not specified, set to 5s)
-th, --thumb : Set thumbnail parameters (x:y:quality) or none
-d, --demo : Run a demo mode (cycle through range of camera options, no capture)
-e, --encoding : Encoding to use for output file (jpg, bmp, gif, png)
-x, --exif : EXIF tag to apply to captures (format as 'key=value') or none
-tl, --timelapse : Timelapse mode. Takes a picture every ms. %d == frame number (Try: -o img_%04d.jpg)
-fp, --fullpreview : Run the preview using the still capture resolution (may reduce preview fps)
-k, --keypress : Wait between captures for a ENTER, X then ENTER to exit
-s, --signal : Wait between captures for a SIGUSR1 or SIGUSR2 from another process
-g, --gl : Draw preview to texture instead of using video render component
-gc, --glcapture : Capture the GL frame-buffer instead of the camera image
-bm, --burst : Enable 'burst capture mode'
-dt, --datetime : Replace output pattern (%d) with DateTime (MonthDayHourMinSec)
-ts, --timestamp : Replace output pattern (%d) with unix timestamp (seconds since 1970)
-fs, --framestart : Starting frame number in output pattern(%d)
-rs, --restart : JPEG Restart interval (default of 0 for none)
GL parameter commands
-gs, --glscene : GL scene square,teapot,mirror,yuv,sobel,vcsm_square
-gw, --glwin : GL window settings <'x,y,w,h'>
Common Settings commands
-?, --help : This help information
-w, --width : Set image width
-h, --height : Set image height
-o, --output : Output filename (to write to stdout, use '-o -'). If not specified, no file is saved
-v, --verbose : Output verbose information during run
-cs, --camselect : Select camera . Default 0
-md, --mode : Force sensor mode. 0=auto. See docs for other modes available
-gps, --gpsdexif : Apply real-time GPS information to output (e.g. EXIF in JPG, annotation in video (requires libgps.so.23)
Preview parameter commands
-p, --preview : Preview window settings <'x,y,w,h'>
-f, --fullscreen : Fullscreen preview mode
-op, --opacity : Preview window opacity (0-255)
-n, --nopreview : Do not display a preview window
-dn, --dispnum : Display on which to display the preview window (dispmanx/tvservice numbering)
Image parameter commands
-sh, --sharpness : Set image sharpness (-100 to 100)
-co, --contrast : Set image contrast (-100 to 100)
-br, --brightness : Set image brightness (0 to 100)
-sa, --saturation : Set image saturation (-100 to 100)
-ISO, --ISO : Set capture ISO
-vs, --vstab : Turn on video stabilisation
-ev, --ev : Set EV compensation - steps of 1/6 stop
-ex, --exposure : Set exposure mode (see Notes)
-fli, --flicker : Set flicker avoid mode (see Notes)
-awb, --awb : Set AWB mode (see Notes)
-ifx, --imxfx : Set image effect (see Notes)
-cfx, --colfx : Set colour effect (U:V)
-mm, --metering : Set metering mode (see Notes)
-rot, --rotation : Set image rotation (0, 90, 180, or 270)
-hf, --hflip : Set horizontal flip
-vf, --vflip : Set vertical flip
-roi, --roi : Set region of interest (x,y,w,d as normalised coordinates [0.0-1.0])
-ss, --shutter : Set shutter speed in microseconds
-awbg, --awbgains : Set AWB gains - AWB mode must be off
-drc, --drc : Set DRC Level (see Notes)
-st, --stats : Force recomputation of statistics on stills capture pass
-a, --annotate : Enable/Set annotate flags or text
-3d, --stereo : Select stereoscopic mode
-dec, --decimate : Half width/height of stereo image
-3dswap, --3dswap : Swap camera order for stereoscopic
-ae, --annotateex : Set extra annotation parameters (text size, text colour(hex YUV), bg colour(hex YUV), justify, x, y)
-ag, --analoggain : Set the analog gain (floating point)
-dg, --digitalgain : Set the digital gain (floating point)
-set, --settings : Retrieve camera settings and write to stdout
-fw, --focus : Draw a window with the focus FoM value on the image.
Notes
Exposure mode options :
off,auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,antishake,fireworks
Flicker avoid mode options :
off,auto,50hz,60hz
AWB mode options :
off,auto,sun,cloud,shade,tungsten,fluorescent,incandescent,flash,horizon,greyworld
Image Effect mode options :
none,negative,solarise,sketch,denoise,emboss,oilpaint,hatch,gpen,pastel,watercolour,film,blur,saturation,colourswap,washedout,posterise,colourpoint,colourbalance,cartoon
Metering Mode options :
average,spot,backlit,matrix
Dynamic Range Compression (DRC) options :
off,low,med,high
libcameraのヘルプ
pi@raspberrypi:~ $ libcamera-apps/build/libcamera-hello --help
Valid options are:
-h [ --help ] [=arg(=1)] (=0) Print this help message
-v [ --verbose ] [=arg(=1)] (=0) Output extra debug and diagnostics
--info-text arg (=#%frame (%fps fps) exp %exp ag %ag dg %dg)
Sets the information string on the
titlebar. Available values:%frame
(frame number), %fps (framerate) %exp
(shutter speed), %ag (analogue gain)%dg
(digital gain), %rg (red colour gain),
%bg (blue colour gain),%focus (focus
FoM value), %aelock (AE locked status)
--width arg (=0) Set the output image width (0 = use
default value)
--height arg (=0) Set the output image height (0 = use
default value)
-t [ --timeout ] arg (=5000) Time (in ms) for which program runs
-o [ --output ] arg Set the output file name
--rawfull [=arg(=1)] (=0) Force use of full resolution raw frames
-n [ --nopreview ] [=arg(=1)] (=0) Do not show a preview window
-p [ --preview ] arg (=0,0,0,0) Set the preview window dimensions,
given as x,y,width,height e.g.
0,0,640,480
-f [ --fullscreen ] [=arg(=1)] (=0) Use a fullscreen preview window
--hflip [=arg(=1)] (=0) Request a horizontal flip transform
--vflip [=arg(=1)] (=0) Request a vertical flip transform
--rotation arg (=0) Request an image rotation, 0 or 180
--roi arg (=0,0,0,0) Set region of interest (digital zoom)
e.g. 0.25,0.25,0.5,0.5
--shutter arg (=0) Set a fixed shutter speed
--analoggain arg (=0) Set a fixed gain value (synonym for
'gain' option)
--gain arg Set a fixed gain value
--metering arg (=centre) Set the metering mode (centre, spot,
average, custom)
--exposure arg (=normal) Set the exposure mode (normal, sport)
--ev arg (=0) Set the EV exposure compensation, where
0 = no change
--awb arg (=auto) Set the AWB mode (auto, incandescent,
tungsten, fluorescent, indoor,
daylight, cloudy, custom)
--awbgains arg (=0,0) Set explict red and blue gains (disable
the automatic AWB algorithm)
--flush [=arg(=1)] (=0) Flush output data as soon as possible
--wrap arg (=0) When writing multiple output files,
reset the counter when it reaches this
number
--brightness arg (=0) Adjust the brightness of the output
images, in the range -1.0 to 1.0
--contrast arg (=1) Adjust the contrast of the output
image, where 1.0 = normal contrast
--saturation arg (=1) Adjust the colour saturation of the
output, where 1.0 = normal and 0.0 =
greyscale
--sharpness arg (=1) Adjust the sharpness of the output
image, where 1.0 = normal sharpening
--framerate arg (=30) Set the fixed framerate for preview and
video modes
--denoise arg (=auto) Sets the Denoise operating mode: auto,
off, cdn_off, cdn_fast, cdn_hq
--viewfinder-width arg (=0) Width of viewfinder frames from the
camera (distinct from the preview
window size
--viewfinder-height arg (=0) Height of viewfinder frames from the
camera (distinct from the preview
window size)
libcamera-jpegのオプション
pi@raspberrypi:~/libcamera-apps/build $ ./libcamera-jpeg --help
Valid options are:
-h [ --help ] [=arg(=1)] (=0) Print this help message
-v [ --verbose ] [=arg(=1)] (=0) Output extra debug and diagnostics
--info-text arg (=#%frame (%fps fps) exp %exp ag %ag dg %dg)
Sets the information string on the
titlebar. Available values:%frame
(frame number), %fps (framerate) %exp
(shutter speed), %ag (analogue gain)%dg
(digital gain), %rg (red colour gain),
%bg (blue colour gain),%focus (focus
FoM value), %aelock (AE locked status)
--width arg (=0) Set the output image width (0 = use
default value)
--height arg (=0) Set the output image height (0 = use
default value)
-t [ --timeout ] arg (=5000) Time (in ms) for which program runs
-o [ --output ] arg Set the output file name
--rawfull [=arg(=1)] (=0) Force use of full resolution raw frames
-n [ --nopreview ] [=arg(=1)] (=0) Do not show a preview window
-p [ --preview ] arg (=0,0,0,0) Set the preview window dimensions,
given as x,y,width,height e.g.
0,0,640,480
-f [ --fullscreen ] [=arg(=1)] (=0) Use a fullscreen preview window
--hflip [=arg(=1)] (=0) Request a horizontal flip transform
--vflip [=arg(=1)] (=0) Request a vertical flip transform
--rotation arg (=0) Request an image rotation, 0 or 180
--roi arg (=0,0,0,0) Set region of interest (digital zoom)
e.g. 0.25,0.25,0.5,0.5
--shutter arg (=0) Set a fixed shutter speed
--analoggain arg (=0) Set a fixed gain value (synonym for
'gain' option)
--gain arg Set a fixed gain value
--metering arg (=centre) Set the metering mode (centre, spot,
average, custom)
--exposure arg (=normal) Set the exposure mode (normal, sport)
--ev arg (=0) Set the EV exposure compensation, where
0 = no change
--awb arg (=auto) Set the AWB mode (auto, incandescent,
tungsten, fluorescent, indoor,
daylight, cloudy, custom)
--awbgains arg (=0,0) Set explict red and blue gains (disable
the automatic AWB algorithm)
--flush [=arg(=1)] (=0) Flush output data as soon as possible
--wrap arg (=0) When writing multiple output files,
reset the counter when it reaches this
number
--brightness arg (=0) Adjust the brightness of the output
images, in the range -1.0 to 1.0
--contrast arg (=1) Adjust the contrast of the output
image, where 1.0 = normal contrast
--saturation arg (=1) Adjust the colour saturation of the
output, where 1.0 = normal and 0.0 =
greyscale
--sharpness arg (=1) Adjust the sharpness of the output
image, where 1.0 = normal sharpening
--framerate arg (=30) Set the fixed framerate for preview and
video modes
--denoise arg (=auto) Sets the Denoise operating mode: auto,
off, cdn_off, cdn_fast, cdn_hq
--viewfinder-width arg (=0) Width of viewfinder frames from the
camera (distinct from the preview
window size
--viewfinder-height arg (=0) Height of viewfinder frames from the
camera (distinct from the preview
window size)
-q [ --quality ] arg (=93) Set the JPEG quality parameter
-x [ --exif ] arg Add these extra EXIF tags to the output
file
--timelapse arg (=0) Time interval (in ms) between timelapse
captures
--framestart arg (=0) Initial frame counter value for
timelapse captures
--datetime [=arg(=1)] (=0) Use date format for output file names
--timestamp [=arg(=1)] (=0) Use system timestamps for output file
names
--restart arg (=0) Set JPEG restart interval
-k [ --keypress ] [=arg(=1)] (=0) Perform capture when ENTER pressed
-s [ --signal ] [=arg(=1)] (=0) Perform capture when signal received
--thumb arg (=320:240:70) Set thumbnail parameters as
width:height:quality
-e [ --encoding ] arg (=jpg) Set the desired output encoding, either
jpg, png, rgb, bmp or yuv420
-r [ --raw ] [=arg(=1)] (=0) Also save raw file in DNG format
--latest arg Create a symbolic link with this name
to most recent saved file