Connecting an analog camera to a raspberry pi. Video surveillance server using Raspberry Pi. Creating timelapse video
Let's look at methods for properly connecting the camera to the Raspberry Pi and working with it through the terminal window and using the Python programming language.Related materials:
When connecting the camera to the Raspberry, remember the following:
- The camera is afraid of static electricity; it is advisable to touch it during operation through antistatic material
- the camera consumes 250 mA - when using a mediocre Malina power supply, connecting the camera may cause a lack of power when the camera is actively working
- there is no microphone in the camera
- the top of the camera is located on the side opposite to the cable exit, but there is a special command to reflect the image vertically - more on that below.
Connection
It is advisable to connect the camera to a switched off Raspberry. You can quickly turn off Raspberry with the commandsudo shutdown now
The CSI daisy chain connector is located next to HDMI: The advantage of connecting the camera through this connector, unlike USB, is that it relieves the processor when transferring data via the CSI interface
For ease of camera fixation there is ready-made solutions, for example - Acrylic holder.
![](https://i2.wp.com/systop.ru/uploads/posts/2018-05/1527699779_vydelenie_298.png)
![](https://i0.wp.com/systop.ru/uploads/posts/2018-05/1527699865_vydelenie_300.png)
![](https://i2.wp.com/systop.ru/uploads/posts/2018-05/1527699957_vydelenie_301.png)
To work with the camera, Raspbian already has the necessary utilities and drivers preinstalled. Let's update the packages to use the latest versions: sudo apt-get update -y sudo apt-get dist-upgrade -y If everything is done correctly, let's try to get a test frame from the camera - create a folder for photos, go to it and execute the image capture command: mkdir ~/pi_cam/ cd ~/pi_cam/ raspistill -v -o test.jpg
![](https://i0.wp.com/systop.ru/uploads/posts/2018-05/1527700014_vydelenie_302.png)
The following packages for working with the camera are preinstalled in Raspbian OS:
- raspivid, raspvidyuv - video capture
- raspistill, raspiyuv - taking photos
All utilities are launched from the terminal and are quite easy to use.
Packages with names ending in “yuv” do not use the encoding component - they store the “raw” unprocessed information received by the camera sensor. Let's look at working with each package, but first we'll get acquainted with the list of camera parameters common to all packages, and then we'll look at specific arguments and specific examples their applications.
Common parameters
Let's look at the parameter values. It is worth noting that:- If an argument is not specified when calling the utility, its default value is used.
- IF THE “ALLOWED VALUES RANGE” COLUMN IS EMPTY, then no additional values need to be passed - just passing the argument itself is enough.
- The preview is shown only on a physical monitor connected to the Raspberry. If you access Raspberry via remote desktop (VNC), the preview will not be shown at any settings since the preview image is sent directly to the monitor on top of the rest of the information
- Similar to watching videos via desktop
Argument | Description | Valid range | Default value |
-p | Preview Window Options | width, height, x-coordinate, y-coordinate | |
-f | Full screen preview | no |
|
-n | No preview | ||
-op | Preview window transparency | 0...255 | 255 |
-sh | Sharpness | -100...100 | 0 |
-co | Contrast | -100...100 | 0 |
-br | Illumination | 0...100 | 50 |
-sa | Saturation | -100...100 | 0 |
-ISO | Camera sensor sensitivity | -100...100 | 0 |
-vs | Video stabilization (video only) | no |
|
-ev | Exposure compensation | -10...10 | 0 |
-ex | Exposition |
| auto |
-awb | White balance |
| auto |
-ifx | Various effects | none, negative, solarise, posterise, whiteboard, blackboard, sketch, denoise, emboss, oilpaint, hatch, gpen, pastel, watercolor, film, blur, saturation, colorswap, washedout, colorpoint, colorbalance, cartoon | none |
-cfx | Color balance | 0...255:0...255 | 128:128 |
-mm | Exposure metering |
| average |
-rot | Turn | 0 ... 359 | 0 |
-hf | Horizontal reflection | No |
|
-vf | Vertical reflection | No |
|
-roi | Sensor ROI | coordinates from the upper left corner and the width and height of the area 0 … 1,0 … 1,0 … 1,0 … 1 | 0,0,1,1 |
-ss | Shutter speed | in microseconds | 6000000 |
-drc | Dynamic range compression | off |
|
-st | show statistics | No |
raspistill - photo capture
This utility produces an encoded compressed image, and to perform this action there are quite a few parameters passed as arguments when running raspistill.Arguments
Argument | Description | Valid range | Default value |
-w | Width | 0...max | Max |
-h | Height | 0...max | Max |
-q | Quality | 0...100 | 75 |
-o | File name | the path to the file | - |
-v | Output to terminal | Information about the capture process | no |
-t | Delay before action | in milliseconds | 0 |
-tl | Time lapse | example: -tl 2000 -o image%04d.jpg 2000 - interval %04d - 4-digit number pattern | - |
-e | Encoding to format | jpg, bmp, gif, and png | jpg |
-x | Adding EXIF tags | up to 32 tags | - |
-r | Storing a Bayer Array in the Meta Data of an Encoded Image | - |
Examples
Let's look at specific examples of using raspistill:Capture a standard image after 2 seconds and save it to the image.jpg file (in the folder you are currently in). The resolution will be standard (maximum) raspistill -t 2000 -o image.jpg The same thing, but in a resolution of 640x480 raspistill -o image.jpg -w 640 -h 480 Capture an image with a reduced quality of 5% and save it to a file image.jpg (in the folder you are currently in). With this quality, the image size will be significantly smaller raspistill -o image.jpg -q 5 Obtaining an image encoded in PNG format and saving it to the file image.png raspistill -o image.png –e png Obtaining a standard image with two embedded EXIF tags: Artist - Boris, GPS altitude - 123.5 m raspistill -o image.jpg -x IFD0.Artist=Boris -x GPS.GPSAltitude=1235/10 Creating a time-lapse set of images that will be captured at intervals of 10 seconds throughout 10 minutes (600,000 ms) and be called image_num_001_today.jpg, image_num_002_today.jpg and so on. The final image will be named latest.jpg raspistill -t 600000 -tl 10000 -o image_num_%03d_today.jpg -l latest.jpg Capture images when you press Enter, the files will be saved side by side and named my_pics01.jpg my_pics02.jpg etc . raspistill -t 0 -k -o my_pics%02d.jpg
raspiyuv
The launch arguments are exactly the same as those of raspistill (see above), of which only the following are NOT AVAILABLE:-q - quality
-e - specifying the target image format
-x - Add EXIF tags
-r - Store a Bayer array in the Meta data of the encoded image
However, there is an OWN argument
-rgb - saving “raw” raw data in RGB888 format (8 bits/channel)
raspivid - video capture
Launch parameters
Argument | Description | Valid range | Default value |
-w | Width | 0...max | 1920 |
-h | Height | 0...max | 1080 |
-b | Video bitrate | number of bits per second. 10Mbits/s is set -b 10000000 | |
-o | File name | the path to the file | - |
-v | Output to terminal | Information about the capture process | |
-t | Delay before action | in milliseconds | 0 |
-fps | Framerate | Number of frames per second 2...30 | |
-k | Start/stop recording by pressing Enter | the process is interrupted by pressing “X” | |
-sg | Saving video segments with a fixed duration into separate files | Set the duration of one segment and file mask -sg 3000 -o video%04d.h264 | |
-wr | Limiting the maximum number of files during segmentation | Used with the -sg argument and essentially implements cyclic rewriting as in DVRs |
Let's look at specific examples:
Recording a 5-second standard video (1920x1080, 30 frames/sec) and saving to a file video.h264 raspivid -t 5000 -o video.h264 Recording a 5-second video with a resolution of 1080p and a specific bitrate of 3.5Mbits/s and saving to file video.h264 raspivid -t 5000 -o video.h264 -b 3500000 Record 5 seconds of standard definition video at 5fps frame rate and save to file video.h264 raspivid -t 5000 -o video.h264 -f 5 If a monitor is connected to the Raspberry via HDMI, the recorded video can be viewed using the omxplayer player: sudo apt-get install omxplayer #if the player is not yet installed omxplayer video.h264 Video viewing is not available via VNC
Error codes
- 0 - successful completion
- 64 - invalid command sent (syntax error)
- 70 - error in the utility or when communicating with the camera
- 130 - execution was interrupted by the user (key combination Ctrl + C)
PiCamera Library
This is a library for the Python programming language that allows you to simplify and automate work with the Raspberry cameraFull description of the library in English
In modern versions of the Raspbian distribution, the library is already pre-installed, you can check this through the Python console python3 import picamera In case of a failure, you must leave the console by entering the exit() command or by pressing Ctrl + D and install the library with the command sudo apt-get install python3-picamera Working with the camera from Python code similar to the terminal commands discussed above. You can easily get a standard image from a camera directly in the Python console: import picamera #import the camera library camera = picamera.PiCamera() #create a camera object camera.capture("image.jpg") #call the camera image capture method camera .close() #close the camera session The image will be saved to the image.jpg file in the current folder.
Two years ago, when I first started working on multicopters, I had to make a small one. Since the quadcopter was intended to be purely autonomous, all that was required of this remote control was to control the drone during testing and setup.
In principle, the remote control coped with all the tasks assigned to it quite successfully . But there were also serious shortcomings.
- The batteries did not fit into the case, so I had to tape them to the case with electrical tape :)
- The parameters were adjusted using four potentiometers, which turned out to be very sensitive to temperature. You set some values indoors, go outside - and they are already different, they have floated away.
- U Arduino Nano, which I used in the remote control, there are only 8 analog inputs. Four were occupied by tuning potentiometers. One potentiometer served as gas. Two inputs were connected to the joystick. Only one output remained free, and there were many more parameters to configure.
- The only joystick was not a pilot one at all. Controlling the throttle with a potentiometer was also quite frustrating.
- And the remote control didn’t make any sounds, which is sometimes extremely useful.
To eliminate all these shortcomings, I decided to radically redesign the remote control. Both the hardware part and the software. Here's what I wanted to do:
- Make a large case so that you can stuff everything you want now (including batteries) into it, and whatever you want later.
- Somehow solve the problem with the settings, not by increasing the number of potentiometers. Plus, add the ability to save parameters in the remote control.
- Make two joysticks, like on normal pilot consoles. Well, put the joysticks themselves Orthodox.
New building
The idea is extremely simple and effective. We cut out two plates from plexiglass or other thin material and connect them with racks. The entire contents of the case are attached to either the top or bottom plate.
Controls and Menus
To control a bunch of parameters, you either need to place a bunch of potentiometers on the remote control and add an ADC, or make all the settings through the menu. As I already said, adjusting with potentiometers is not always a good idea, but you shouldn’t give it up either. So, it was decided to leave four potentiometers in the remote control and add a full menu.
To navigate through the menu and change parameters, buttons are usually used. Left, right, up, down. But I wanted to use an encoder instead of buttons. I got this idea from a 3D printer controller.
Of course, due to the addition of the menu, the remote control code has expanded several times. To begin with, I added only three menu items: "Telemetry", "Parameters" and "Store params". The first window displays up to eight different indicators. So far I only use three: battery power, compass and altitude.
In the second window, six parameters are available: PID controller coefficients for the X/Y, Z axes and accelerometer correction angles.
The third item allows you to save parameters in EEPROM.
Joysticks
I didn’t think long about the choice of pilot joysticks. It so happened that I got the first Turnigy 9XR joystick from a colleague in the quadcopter business - Alexander Vasiliev, the owner of the well-known website alex-exe.ru. I ordered the second one directly from Hobbyking.
The first joystick was spring-loaded in both coordinates - to control yaw and pitch. The second one I took was the same one, so that I could then convert it into a joystick to control traction and rotation.
Nutrition
In the old remote control I used a simple LM7805 voltage regulator, which was fed with a bunch of 8 AA batteries. A terribly inefficient option, in which 7 volts were spent on heating the regulator. 8 batteries - because there was only such a compartment at hand, and LM7805 - because at that time this option seemed to me the simplest, and most importantly, the fastest.
Now I decided to act wiser and installed a fairly effective regulator on the LM2596S. And instead of 8 AA batteries, I installed a compartment for two LiIon 18650 batteries.
Result
Putting everything together, we got this device. Inside view.
But with the lid closed.
The cap on one potentiometer and the caps on the joysticks are missing.
Finally, a video about how settings are configured through the menu.
Bottom line
The remote control is physically assembled. Now I am working on finalizing the code for the remote control and quadcopter in order to return them to their former strong friendship.
While setting up the remote control, shortcomings were identified. Firstly, the lower corners of the remote control rest in your hands: (I’ll probably redesign the plates a little, smooth out the corners. Secondly, even a 16x4 display is not enough for a beautiful telemetry display - I have to shorten the parameter names to two letters. In the next version of the device I will install a dot display , or immediately a TFT matrix.
The Raspberry Pi single board computer allows you to create really interesting and useful things: from multimedia centers to home automation systems. By connecting various modules to the Raspberry Pi, you can significantly expand the functionality of this minicomputer.
One of these additional plug-ins is a camera, which allows you to take pictures or shoot videos. Today there are a number of cameras for Raspberry Pi on the market, and in this article we will give a short review of them.
Let's look at six of the most popular cameras: ZeroCam Noir, ZeroCam FishEye, Raspberry Pi Compatible Fisheye Camera, Raspberry Pi Camera V2, Raspberry Pi Camera V2 Noir and Raspberry Pi Camera 1.3.
ZeroCam Noir is a camera module for Raspberry Pi Zero or Raspberry Pi Zero W, so if you want to use it in Raspberry Pi 3 or 2, you will need to use an adapter cable. This camera does not have an IR filter on the lens, making it ideal for low-light photography. Here are some of its main characteristics: 5 megapixel sensor, 2592 × 1944 pixels, 1080p at 30 FPS (or 60 FPS at 720p, 90 FPS at 480p), focal length 3.60 mm, 53.50 degrees horizontal, 41.41 degrees vertical, approx. board dimensions with camera: 60 x 11.4 x 5.1 mm.
This is the fisheye version of the ZeroCam, which means it has a wide-angle image. This camera is also made for Pi Zero or Pi Zero W, so to use it with another Pi panel you need an adapter cable.
This is a Raspberry Pi compatible fisheye camera that can be easily found on various online trading platforms such as AliExpress, TaoBao, eBay. It is characterized by a wide-angle view of 175º. It is based on the Omnivision 5647 sensor with a resolution of 5 megapixels (2592 x 1944 pixels).
This camera is equipped with an 8-megapixel Sony IMX219 image sensor with a fixed focal lens, capable of displaying 3280×2464 pixel static images, it supports 1080p30, 720p60 and 640×480p90 videos. The camera is compatible with all Raspberry Pi boards, but if you want to use it with the Pi Zero, you need an adapter cable.
This camera has all the features of the Raspberry Pi Camera V2 module, but it does not have an IR filter. This means that it is almost an ideal camera for shooting in the dark.
Raspberry Pi Camera 1.3 is the predecessor to the V2 module. It is equipped with a 5-megapixel OmniVision OV5647 sensor.
Comparison of field of view and image quality of cameras for Raspberry Pi
In this test, all cameras are installed at a distance of 1 meter from the test image. The results are as follows:
Comparison of image quality and color rendition of Raspberry Pi cameras when zooming
Comparison of shooting quality at night
The results below show several night photography-ready cameras doing the same thing. test image in very low light in the dark.
conclusions
All cameras perform a little better than expected from such cheap modules. Unfortunately, there's no all-in-one camera among them, and there's a trade-off to be made as there don't seem to be any wide-angle (fisheye) cameras with the IR cut filter removed. So if you want a wide angle, you'll need regular lighting, and conversely, at night you're unlikely to get wide-angle shots.
Good day!
On New Year's Eve, I had the idea to build some kind of video surveillance. I had everything I needed on hand:
- Raspberry Pi Model B single board computer
- Webcam LOGITECH HD Webcam C270
Acquaintance
So, first, let's get acquainted with the main “component”:Raspberry Pi appearance:
Characteristics:
- Broadcom BCM2835 700MHz ARM1176JZFS processor with FPU and Videocore 4 GPU
- GPU provides Open GL ES 2.0, hardware-accelerated OpenVG, and 1080p30 H.264 high-profile decode
- GPU is capable of 1Gpixel/s, 1.5Gtexel/s or 24GFLOPS with texture filtering and DMA infrastructure
- 512MB RAM
- Boots from SD card, running a version of the Linux operating system
- 10/100 BaseT Ethernet socket
- HDMI video out socket
- 2 x USB 2.0 sockets
- RCA composite video out socket
- SD card socket
- Powered from microUSB socket
- 3.5mm audio out jack
- Raspberry Pi HD video camera connector
- Size: 85.6 x 53.98 x 17mm"
A list of officially supported distributions can be found. I chose Raspbian without a graphical shell.
The installation process is quite simple and does not require detailed description, so I will list the main facts that are worth paying attention to:
- Setting the time zone
- Setting the computer name
- Enabling SSH access
- System update
Preparation
First, let's install all the necessary packages:sudo apt-get install imagemagick libav-tools libjpeg8-dev subversion
Then download and assemble mjpg-streamer:
sudo svn co https://svn.code.sf.net/p/mjpg-streamer/code/mjpg-streamer/ mjpg-streamer cd mjpg-streamer make
Because We will store all data in the cloud, we will set up work with remote file system via WebDAV:
sudo apt-get install davfs2 sudo mkdir /mnt/dav sudo mount -t davfs https://webdav.yandex.ru /mnt/dav -o uid=pi,gid=pi
In order not to enter your username and password every time, you need to add them to the file
/etc/davfs2/secrets
/mnt/dav user password
The working process
Let's add commands to /etc/rc.local to mount WebDAV and run the script for broadcasting to the network:mount -t davfs https://webdav.yandex.ru /mnt/dav -o uid=pi,gid=pi cd /home/pi/mjpg-streamer && ./mjpg_streamer -i "./input_uvc.so" -o "./output_http.so -w ./www"
Now, by going to http://:8080/ we will get access to the camera. All that remains is to forward the port on the router and you can access the camera outside the local network.
Creating timelapse video
First of all, we need to get an image from the camera. Because it is already occupied (the image is broadcast by the web server), then we will use the opportunity to receive the current image from the web server:curl http://localhost:8080/?action=snapshot > out.jpg
If we want to draw the date of the photo on the image, then we can use the convert command
timestamp=`stat -c %y out.jpg` convert out.jpg -fill black -fill white -pointsize 15 -draw "text 5.15 "$(timestamp:0:19)"" out_.jpg
Full version script:
#!/bin/bash filename=$(perl -e "print time") foldername=$(date --rfc-3339=date) curl http://localhost:8080/?action=snapshot > $filename timestamp=` stat -c %y $filename` mkdir /mnt/dav/out/$foldername convert $filename -fill black -fill white -pointsize 15 -draw "text 5.15 "$(timestamp:0:19)"" /mnt /dav/out/$foldername/$filename.jpg rm $filename
The video is assembled using the avconv command:
avconv -r 10 -i %06d.jpg -r 10 -vcodec mjpeg -qscale 1 out.avi
Full version of the video assembly script:
#!/bin/bash filename=$(date --rfc-3339=date) i=0 for f in `ls -tr /mnt/dav/out/$filename/*.jpg 2>/dev/null` do newf=`printf %06d $i`.jpg echo $f "-->" $newf mv $f $newf i=$((i+1)) done rmdir -R /mnt/dav/out/$filename/ avconv -r 10 -i %06d.jpg -r 10 -vcodec mjpeg -qscale 1 /mnt/dav/$filename.avi rm *.jpg
Now all that remains is to register the execution of scripts in the Cron scheduler:
* * * * * pi bash /home/pi/cam.sh 59 23 * * * pi bash /home/pi/build.sh
Example video
Conclusion
This approach helps eliminate the need to spend a lot of time watching videos, and also reduces the cost of the final product. Thanks to the presence of a full-fledged OS, it becomes possible to expand the functionality in the right direction.Because This computer has sufficient performance to receive, store, process and transmit video from a camera (for example, from a USB camera) via wifi to other devices. There are special cameras for Raspberry PI that connect to a special connector on it and USB cameras that connect to any USB port on Raspberry PI. Because USB cameras, as a rule, are much cheaper than special ones (albeit worse), so next we will consider using a USB camera with Raspberry PI. There are a number of programs for capturing video from a USB camera, or you can write your own, but for the sake of simplicity, first let’s look at capturing and transmitting video using the motion program. To install the motion program on Raspberry PI, you must first connect to it through the Putty program (or any other terminal program with the ability to communicate via SSH) (for information on how to do this, see the previous article “Raspberry PI 3 setting up and managing GPIO via WIFI”) . After connecting to the Raspberry PI, you need to update the system using the commands
Sudo apt-get update
Sudo apt-get upgrade
After a successful system update, you need to install the motion program with the command
Sudo apt-get install motion
During installation you may be asked the question "Do you want to continue?" after which you will need to enter the letter "Y". After installing the motion program, you will need to make some changes to the configuration files. Open the motion.conf file in the nano editor with the command
Sudo nano /etc/motion/motion.conf
Then
Replaced by
Next, we will find other lines to change, to do this, press the key combination CTRL+W, enter “stream_localhost” and press enter, after that the required line should be found, if it is not found, then the variable “stream_localhost” is called something else, for example “webcam_localhost” or something something like that. After the line with this variable is found, you need to
Stream_localhost on
replaced by
Stream_maxrate 1
And replace with
Stream_maxrate 100
Replaced by
Then
Minimum_frame_time 0
Replaced by
Minimum_frame_time 1
The latter is done so that frames are output once per second - this does not look very good, but the video will not disappear if the image changes suddenly. The purpose of each variable can be read in the comments.
Now save the changes by pressing CTRL+O and enter, then press CTRL+X and exit nano editor. Now let's edit another file, to do this we enter the command
Sudo nano /etc/default/motion
And replace the line
Start_motion_daemon=no
Start_motion_daemon=yes
Then save the changes by pressing CTRL+O and enter and then press CTRL+X and exit the nano editor. Now you can start video transfer (the USB camera must be connected to one of the ports) with the command
Sudo service motion start
Stop with command
Sudo service motion stop
In order to see the video, you need to open the browser, and enter the IP address of the Raspberry PI in the address bar, then put a colon and 8081 (IP address of the Raspberry PI: 8081) and press enter, after which the video from the USB camera should appear in the browser. You can see how this is all done, see the result and something else in the video:
Like this in a simple way You can get video from a USB camera connected to Raspberry PI. If it is a Raspberry PI 3 with built-in wifi and powered by a powerbank (or some other portable source of electricity) (for example, this one or a cheaper one, although it is not recommended to use a cheap one, Raspberry PI needs a normal power source to use all its capabilities, it is also very advisable to install a heatsink for the processor and other microcircuits that develop during Raspberry operation, ideally the heatsink should be copper and coated with special black paint), then based on all this you can make some kind of video surveillance system, video camera or something similar.