Pi camera module

From Interaction Station Wiki
Jump to navigation Jump to search

Monkey selfie copyright dispute

https://en.wikipedia.org/wiki/Monkey_selfie_copyright_dispute

Raspberry Pi keyboard shortcuts

https://beebom.com/best-raspberry-pi-keyboard-shortcuts/

The command-line interface

Most of the time, when using computers, we are accessing them using a Graphical User Interface (GUI). So, when you start your laptop, you see a Windows or Mac login screen or your Desktop layout. This command line is a text-based interface for sending commands instead of a graphical one. Before computers could support graphics, users interacted with them via the terminal or command line, and this is still available and commonly used in non-graphical environments such as servers.

Once you log in to the command-line on your Raspberry Pi, the first line will start with the prompt

pi@raspberrypi $ 

This indicates that you have successfully logged in to your Raspberry Pi. You can enter your commands in the commands line in front of this text.

Updating the system Once you turn on your Raspberry Pi, it’s good practice to start off by updating your Raspberry Pi Operating System and it’s sources to the latest version. You can type the following commands to do so.

sudo apt-get update
sudo apt-get upgrade

Other basic commands To change directory, used the cd command

cd /home/pi

To change directory to the parent directory

cd ..

To list the directories and files for the current directory

ls

stands for print working directory and it shows you in which directory you are at

pwd

To make a new directory

mkdir myNewDirectory

Example: mkdir pidir will create a new directory, where “pidir” is the label of the directory.

to change into the new directory would then be:

cd myNewDirectory


clear up all the commands in the current screen and display a clean new screen.

clear

To shut down the Rasberry Pi

sudo poweroff

To reboot

sudo reboot

This will immediately shut down your Raspberry Pi:

sudo shutdown -h now


be careful with these commands


delete files that you no longer need anymore

rm

Example: rm testfile.txt will delete the testfile.txt from its directory

copy files from one directory to another:

cp

Example: cp /home/pi/new/file.txt /home/pi/project/ will copy the file.txt from /home/pi/new/ directory and paste in to /home/pi/project/ directory.


this will act as a cut and paste command where the file will be moved from one directory to another:

mv

However, this command can be used to rename file names that are in the same directory.

Example: mv /home/pi/new/file.txt /home/pi/project/ will move the file.txt from /home/pi/new/ directory to /home/pi/project/ directory.


Example: mv oldproject.txt newproject.txt will change the file name from oldproject to newproject.

CAMERA TYPES!

Three types of Raspberry Pi Camera are available:

the standard Camera Module, the 'NoIR' version, the High Quality (HQ) Camera, and the Night Vision camera.

standard Camera Module & High Quality (HQ) Camera

If you want to take normal pictures and video in well-lit environments, you should use the standard Camera Module; if you want to use special lenses and are looking for the best picture quality, use the HQ Camera Module.

The NoIR Camera Module – so called because it has no infrared, or IR, filter – is designed for use with infrared light sources to take pictures and video in total darkness. If you're building a nest box, security camera, or other project involving night vision, you want the NoIR version – but remember to buy an infrared light source at the same time!

Raspberry Pi Night Vision camera: simular to NoIR camera, except it has 2 Infrarood LEDs.

about Thermal camera:

even though the Thermal camera has a camera in the description, but it works more like arrays of sensors. it requires some deeper knowledge of python and arrays and different libraries. currently, we have a few mlx90640 Thermal camera break out at the interaction station:

we won't go into details in this workshop but if you are interested check out these two links:


https://www.youtube.com/watch?v=XRwbcsbh33w&ab_channel=EverythingSmartHome

https://makersportal.com/blog/2020/6/8/high-resolution-thermal-camera-with-raspberry-pi-and-mlx90640

Installing the camera

the hardware:

Like any hardware add-on, the Camera Module or HQ Camera should only be connected to or disconnected from Raspberry Pi when the power is off and the power cable unplugged. If your Raspberry Pi is turned on, choose Shutdown from the raspberry menu, wait for it to power off, and unplug it.

Carefully hook your fingernails around the sticking-out edges and pull outwards until the connector pulls part-way out. Slide the ribbon cable, with the silver edges downwards and the blue plastic facing upwards, under the flap you just pulled out, then push the flap gently back into place with a click.

The software:

Before you can use the camera, you’ll need to tell Raspberry Pi it has one connected: open the raspberry icon menu, choose the Preferences category, and click Raspberry Pi Configuration. When the tool has loaded, click the Interfaces tab, find the Camera entry in the list, and click on the round radio button to the left of ‘Enabled’ to switch it on (Figure 8-3, overleaf). Click OK, and the tool will prompt you to reboot your Raspberry Pi. Do so and your camera will be ready to use!

Testing the camera in Terminal

To confirm that your Camera Module or HQ Camera is properly installed, and that you’ve enabled the interface in the Raspberry Pi Configuration Tool, you can use the raspistill tool. This, along with raspivid for videos, is designed to capture images from the camera using Raspberry Pi’s command-line interface (CLI).

To test the camera, type the following into the Terminal:

 raspistill -o test.jpg

As soon as you hit ENTER, you’ll see a large picture of what the camera sees appear on screen.

This is called the live preview and,it will last for 5 seconds.

After those 5 seconds are up, the camera will capture a single still picture

and save it in your home folder under the name test.jpg.

If you want to capture another, type the same command again – but make sure to change the output file name,

after the -o, or you’ll save over the top of your first picture!

To see your picture, open the File Manager, you will find an image called test.jpg in your home/pi folder

Control pi camera module in Python:

The most flexible way to control the Camera Module or HQ Camera is using Python, via the handy picamera library. This gives you full control over the camera’s preview, picture, and video capture abilities, and allows you to integrate them into your own programs – even combining them with programs that use the GPIO module through the GPIO Zero library!

. Hello, World!

In the code area, where it says, # Write your code here :-), write the following code:

print( 8 )

Then click the Save button to save the code and run it on the CircuitPlayground.

You should see this message appear in the Serial Dialogue Panel:

code.py output: 8

Change the message to something else. If you want to print characters instead of numbers, you must use quotation marks.

print( "hello" )

Let's program the device to print two things, with a time delay in between the two print statements:

1import time
2print( "hello" )
3time.sleep( 0.5 )
4print( "Nan" )
5time.sleep( 0.5 )

Now let's make a loop, so the message will be running forever:

1import time
2 
3while True:
4 
5    print( "hello" )
6    time.sleep( 0.5 )
7    print( "Nan" )
8    time.sleep( 0.5 )

Indentation and commenting options

Python programs are Space holder Character Sensitive.

To indent the three lines, I selected them all and then pressed the Tab key.

To unindent, select some lines and press Shift-Tab key.

To comment single line: Select the desired lines of code to comment.

press Alt+3 to comment, Alt+4 to un-comment


in python:

only preview

before we start let's update the pi in the terminal:


sudo apt-get update
sudo apt-get install python-picamera python3-picamera


1from picamera import PiCamera
2from time import sleep
3
4camera=PiCamera()
5camera.start_preview()
6sleep(2)
7camera.stop_preview()


if you get suck here with full screen

you press [Ctrl] [Alt] [Del] to force reboot.

keyboard controlled preview

 1from picamera import PiCamera
 2from time import sleep
 3
 4
 5while True:
 6    inkey = input()
 7    if inkey=="s":
 8        camera = PiCamera()
 9        camera.start_preview()
10        sleep (3)
11#python3 use input() python 2 use raw_input()
12    if inkey=="k":
13        camera.stop_preview()


take one picture

1from picamera import PiCamera
2
3camera = PiCamera()
4camera.start_preview()
5
6camera.capture('image.jpg')
7camera.stop_preview()
8print("Done")

Advanced camera settings

camera.awb_mode = 'auto' This sets the automatic white balance mode of the camera and can be set to any one of the following modes:

off, auto, sunlight, cloudy, shade, tungsten, fluorescent, incandescent, flash, or horizon.

If you find your pictures and videos look a little blue or yellow, try a different mode.


camera.brightness = 50

This sets the brightness of the camera image, from darkest at 0 to brightest at 100.

camera.color_effects = None

This changes the colour effect currently in use by the camera. Normally, this setting should be left alone, but if you provide a pair of numbers you can alter the way the camera records colour: try (128, 128) to create a black and white image.

camera.contrast = 0

This sets the contrast of the image. A higher number will make things look more dramatic and stark; a lower number will make things look more washed out. You can use any number between -100 for minimum contrast and 100 for maximum contrast.

camera.crop = (0.0, 0.0, 1.0, 1.0)

This allows you to crop the image, cutting parts off the sides and tops to capture only the part of the image you need. The numbers represent X coordinate, Y coordinate, width, and height, and by default captures the full image. Try reducing the last two numbers – 0.5 and 0.5 is a good starting point – to see what effect this setting has.

camera.exposure_compensation = 0

This sets the exposure compensation of the camera, allowing you to manually control how much light is captured for each image. Unlike changing the brightness setting, this actually controls the camera itself. Valid values range from -25 for a very dark image to 25 for a very bright image.

camera.exposure_mode = 'auto'

This sets the exposure mode, or the logic the Camera Module / HQ Camera uses to decide how an image should be exposed. Possible modes are: off, auto, night, backlight, spotlight, sports, snow, beach, verylong, fixedfps, antishake, and fireworks.

camera.framerate = 30

This sets the number of images captured to create a video per second, or the frame rate. A higher frame rate creates a smoother video, but takes up more storage space. Higher frame rates require a lower resolution to be used, which you can set via camera.resolution.

camera.resolution = (1920, 1080)

This sets the resolution of the captured picture or video, represented by two numbers for width and height. Lower resolutions will take up less storage space and allow you to use a higher frame rate; higher resolutions are better quality but take up more storage space.


camera.hflip = False

This flips the camera image across the horizontal, or X, axis when set to True.

camera.vflip = False

This flips the camera image across the vertical, or Y, axis when set to True.

camera.image_effect = 'none'

This applies one of a range of image effects to the video stream, which will be visible in the preview as well as the saved images and videos. Possible effects are: blur, cartoon, colorbalance, colorpoint, colorswap, deinterlace1, deinterlace2, denoise, emboss, film, gpen, hatch, negative, none, oilpaint, pastel, posterise, saturation, sketch, solarize,washedout, andwatercolor.

camera.ISO = 0

This changes the ISO setting of the camera, which affects how sensitive it is to light. By default, the camera adjusts this automatically depending on the available light. You can set the ISO yourself using one of the following values: 100, 200, 320, 400, 500, 640, 800. The higher the ISO, the better the camera will perform in low-light environments but the grainier the image or video it captures.

camera.meter_mode = 'average'

This controls how the camera decides on the amount of available light when setting its exposure. The default averages the amount of light available throughout the whole picture; other possible modes are backlit, matrix, and spot.


camera.rotation = 0

This controls the rotation of the image, from 0 degrees through 90, 180, and 270 degrees. Use this if you can’t position the camera so that the ribbon cable is coming out of the bottom.

camera.saturation = 0

This controls the saturation of the image, or how vibrant colours are. Possible values range from -100 to 100.


camera.sharpness = 0

This controls the sharpness of the image. Possible values range from -100 to 100.

camera.shutter_speed = 0

This controls how quickly the shutter opens and closes when capturing images and videos. You can set the shutter speed manually in microseconds, with longer shutter speeds working better in lower light and faster shutter speeds in brighter light. This should normally be left on its default, automatic, setting.

Capturing moving video

 1from picamera import PiCamera
 2from time import sleep
 3
 4
 5camera = PiCamera()
 6
 7camera.resolution = (1920, 1080)
 8camera.start_recording('/home/pi/Desktop/video.h264')
 9sleep(10)
10camera.stop_recording()

take 10 pictures

 1from picamera import PiCamera
 2
 3camera = PiCamera()
 4camera.start_preview()
 5
 6for i in range(20):
 7    camera.capture('image{0:04d}.jpg'.format(i))
 8    
 9  
10camera.stop_preview()
11print("Done taking 10 photos!")

timelapse

 1from picamera import PiCamera
 2from os import system
 3import datetime
 4from time import sleep
 5
 6tlminutes = 10 #set this to the number of minutes you wish to run your timelapse camera
 7secondsinterval = 1 #number of seconds delay between each photo taken
 8fps = 30 #frames per second timelapse video
 9numphotos = int((tlminutes*60)/secondsinterval) #number of photos to take
10print("number of photos to take = ", numphotos)
11
12dateraw= datetime.datetime.now()
13datetimeformat = dateraw.strftime("%Y-%m-%d_%H:%M")
14print("RPi started taking photos for your timelapse at: " + datetimeformat)
15
16camera = PiCamera()
17camera.resolution = (1024, 768)
18
19system('rm /home/pi/Pictures/*.jpg') #delete all photos in the Pictures folder before timelapse start
20
21for i in range(numphotos):
22    camera.capture('/home/pi/Pictures/image{0:06d}.jpg'.format(i))
23    sleep(secondsinterval)
24print("Done taking photos.")
25print("Please standby as your timelapse video is created.")
26
27system('ffmpeg -r {} -f image2 -s 1024x768 -nostats -loglevel 0 -pattern_type glob -i "/home/pi/Pictures/*.jpg" -vcodec libx264 -crf 25  -pix_fmt yuv420p /home/pi/Videos/{}.mp4'.format(fps, datetimeformat))
28#system('rm /home/pi/Pictures/*.jpg')
29print('Timelapse video is complete. Video saved as /home/pi/Videos/{}.mp4'.format(datetimeformat))

GPIOZero and button

Button bb.png

Raspberry-pi-15b.jpeg

1from gpiozero import Button
2
3button = Button(2)
4
5while True:
6    if button.is_pressed:
7        print("Button is pressed")
8    else:
9        print("Button is not pressed")
1from gpiozero import Button
2
3button = Button(2)
4
5button.wait_for_press()
6print("Button was pressed")

https://gpiozero.readthedocs.io/en/stable/recipes.html#button

Push-button stop-motion animation

take one photo:

1from picamera import PiCamera
2from gpiozero import Button
3
4camera = PiCamera()
5button = Button(2)
6camera.start_preview()
7button.wait_for_press()
8camera.capture('/home/pi/Desktop/image.jpg')
9camera.stop_preview()

Having to restart your program every time you capture a picture for your animation isn’t very good, so you need to change it to run in a loop. Unlike the previous loops you’ve created, though, this one needs a way to close gracefully – otherwise, if you stop the program while the camera preview is showing, you won’t be able to see the desktop anymore! To do this, you need to use two special instructions: try and except.

we need to create a folder on the desktop called animation and after we are done with the stop motion animation. we can quit the full screen preview by press Ctrl-c this will raise the KeyboardInterrupt exception. and break the while loop.


 1# create a folder called "animation" on Desktop
 2
 3from picamera import PiCamera
 4from time import sleep
 5from gpiozero import Button
 6
 7
 8camera = PiCamera()
 9button = Button(2)
10camera.start_preview()
11frame = 1
12while True:
13    try:
14#The new instruction try tells Python to run whatever code is inside – which is going to be the code for capturing images. Type:
15        button.wait_for_press() 
16        camera.capture('/home/pi/Desktop/animation/frame%03d.jpg' % frame) 
17        frame += 1
18    except KeyboardInterrupt:
19        camera.stop_preview()
20        break

Advanced camera settings

camera.awb_mode = 'auto' This sets the automatic white balance mode of the camera and can be set to any one of the following modes:

off, auto, sunlight, cloudy, shade, tungsten, fluorescent, incandescent, flash, or horizon.

If you find your pictures and videos look a little blue or yellow, try a different mode.


camera.brightness = 50

This sets the brightness of the camera image, from darkest at 0 to brightest at 100.

camera.color_effects = None

This changes the colour effect currently in use by the camera. Normally, this setting should be left alone, but if you provide a pair of numbers you can alter the way the camera records colour: try (128, 128) to create a black and white image.

camera.contrast = 0

This sets the contrast of the image. A higher number will make things look more dramatic and stark; a lower number will make things look more washed out. You can use any number between -100 for minimum contrast and 100 for maximum contrast.

camera.crop = (0.0, 0.0, 1.0, 1.0)

This allows you to crop the image, cutting parts off the sides and tops to capture only the part of the image you need. The numbers represent X coordinate, Y coordinate, width, and height, and by default captures the full image. Try reducing the last two numbers – 0.5 and 0.5 is a good starting point – to see what effect this setting has.

camera.exposure_compensation = 0

This sets the exposure compensation of the camera, allowing you to manually control how much light is captured for each image. Unlike changing the brightness setting, this actually controls the camera itself. Valid values range from -25 for a very dark image to 25 for a very bright image.

camera.exposure_mode = 'auto'

This sets the exposure mode, or the logic the Camera Module / HQ Camera uses to decide how an image should be exposed. Possible modes are: off, auto, night, backlight, spotlight, sports, snow, beach, verylong, fixedfps, antishake, and fireworks.

camera.framerate = 30

This sets the number of images captured to create a video per second, or the frame rate. A higher frame rate creates a smoother video, but takes up more storage space. Higher frame rates require a lower resolution to be used, which you can set via camera.resolution.

camera.resolution = (1920, 1080)

This sets the resolution of the captured picture or video, represented by two numbers for width and height. Lower resolutions will take up less storage space and allow you to use a higher frame rate; higher resolutions are better quality but take up more storage space.


camera.hflip = False

This flips the camera image across the horizontal, or X, axis when set to True.

camera.vflip = False

This flips the camera image across the vertical, or Y, axis when set to True.

camera.image_effect = 'none'

This applies one of a range of image effects to the video stream, which will be visible in the preview as well as the saved images and videos. Possible effects are: blur, cartoon, colorbalance, colorpoint, colorswap, deinterlace1, deinterlace2, denoise, emboss, film, gpen, hatch, negative, none, oilpaint, pastel, posterise, saturation, sketch, solarize,washedout, andwatercolor.

camera.ISO = 0

This changes the ISO setting of the camera, which affects how sensitive it is to light. By default, the camera adjusts this automatically depending on the available light. You can set the ISO yourself using one of the following values: 100, 200, 320, 400, 500, 640, 800. The higher the ISO, the better the camera will perform in low-light environments but the grainier the image or video it captures.

camera.meter_mode = 'average'

This controls how the camera decides on the amount of available light when setting its exposure. The default averages the amount of light available throughout the whole picture; other possible modes are backlit, matrix, and spot.


camera.rotation = 0

This controls the rotation of the image, from 0 degrees through 90, 180, and 270 degrees. Use this if you can’t position the camera so that the ribbon cable is coming out of the bottom.

camera.saturation = 0

This controls the saturation of the image, or how vibrant colours are. Possible values range from -100 to 100.


camera.sharpness = 0

This controls the sharpness of the image. Possible values range from -100 to 100.

camera.shutter_speed = 0

This controls how quickly the shutter opens and closes when capturing images and videos. You can set the shutter speed manually in microseconds, with longer shutter speeds working better in lower light and faster shutter speeds in brighter light. This should normally be left on its default, automatic, setting.

getting started with picamera

https://projects.raspberrypi.org/en/projects/getting-started-with-picamera

1.Push button stop motion

https://projects.raspberrypi.org/en/projects/push-button-stop-motion/