Skip to content

Commit 15f01bf

Browse files
authored
Merge pull request #16 from bioimedpellegrino/raspi-camera-version
Added scripts for Picamera2 and dependency installation
2 parents e3b7a44 + 77a198d commit 15f01bf

File tree

9 files changed

+643
-9
lines changed

9 files changed

+643
-9
lines changed

install.sh

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/bin/bash
2+
3+
is_raspberry_pi() {
4+
if grep -q "Raspberry" /proc/cpuinfo || grep -q "BCM" /proc/cpuinfo; then
5+
return 0 # Is raspberry Pi
6+
else
7+
return 1
8+
fi
9+
}
10+
11+
if is_raspberry_pi; then
12+
echo "Raspberry Pi detected. Running Raspberry-specific script..."
13+
14+
echo "Update packages"
15+
sudo apt-get update
16+
17+
echo "Installing libopencv-dev and libatlas-base-dev..."
18+
sudo apt-get install -y libopencv-dev libatlas-base-dev
19+
20+
if ! command -v pip3 &> /dev/null; then
21+
echo "pip3 not found. Installing pip3..."
22+
sudo apt-get install -y python3-pip
23+
fi
24+
25+
echo "Installing Pillow, numpy, scipy, matplotlib..."
26+
pip3 install Pillow numpy scipy matplotlib
27+
28+
echo "Installing opencv-python and opencv-contrib-python..."
29+
pip3 install opencv-python opencv-contrib-python
30+
31+
echo "Installation of dependencies completed for Raspberry Pi!"
32+
33+
else
34+
echo "Non-Raspberry Pi system detected. Running standard script..."
35+
36+
echo "Updating package list..."
37+
sudo apt-get update
38+
39+
echo "Installing libopencv-dev and libatlas-base-dev..."
40+
sudo apt-get install -y libopencv-dev libatlas-base-dev
41+
42+
if ! command -v pip3 &> /dev/null; then
43+
echo "pip3 not found. Installing pip3..."
44+
sudo apt-get install -y python3-pip
45+
fi
46+
47+
if ! command -v virtualenv &> /dev/null; then
48+
echo "virtualenv not found. Installing virtualenv..."
49+
pip3 install virtualenv
50+
fi
51+
52+
echo "Creating a virtual environment..."
53+
virtualenv venv
54+
55+
echo "Activating virtual environment..."
56+
source venv/bin/activate
57+
58+
echo "Installing dependencies: Pillow, numpy, scipy, matplotlib, opencv-python, and opencv-contrib-python..."
59+
pip install Pillow numpy scipy matplotlib opencv-python opencv-contrib-python
60+
61+
if [ -f requirements.txt ]; then
62+
echo "Installing dependencies from requirements.txt..."
63+
pip install -r requirements.txt
64+
else
65+
echo "requirements.txt not found. Skipping installation from requirements file."
66+
fi
67+
68+
echo "Installation of dependencies completed for non-Raspberry Pi system!"
69+
fi

requirements.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,14 @@
1+
contourpy
2+
cycler
3+
fonttools
4+
kiwisolver
5+
matplotlib
16
numpy
7+
opencv-contrib-python
28
opencv-python
9+
packaging
10+
pillow
11+
pyparsing
12+
python-dateutil
13+
scipy
14+
six

src/camera-test/cv_camera_test.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,25 @@
99
# Twitter: @yfrobotics
1010
# Website: https://www.yfrl.org
1111
# ------------------------------------------------------------------------------
12+
# Add src directory to the path
13+
import os
14+
import sys
15+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1216

1317
import cv2
1418
import time
1519
import numpy as np
20+
import time
21+
22+
from utils.picamera_utils import is_raspberry_camera, get_picamera
1623

1724
CAMERA_DEVICE_ID = 0
1825
IMAGE_WIDTH = 320
1926
IMAGE_HEIGHT = 240
27+
IS_RASPI_CAMERA = is_raspberry_camera()
2028
fps = 0
2129

30+
print("Using raspi camera: ", IS_RASPI_CAMERA)
2231

2332
def visualize_fps(image, fps: int):
2433
if len(np.shape(image)) < 3:
@@ -39,15 +48,18 @@ def visualize_fps(image, fps: int):
3948

4049
return image
4150

42-
4351
if __name__ == "__main__":
4452
try:
45-
# create video capture
46-
cap = cv2.VideoCapture(CAMERA_DEVICE_ID)
47-
48-
# set resolution to 320x240 to reduce latency
49-
cap.set(3, IMAGE_WIDTH)
50-
cap.set(4, IMAGE_HEIGHT)
53+
54+
if IS_RASPI_CAMERA:
55+
cap = get_picamera(IMAGE_WIDTH, IMAGE_HEIGHT)
56+
cap.start()
57+
else:
58+
# create video capture
59+
cap = cv2.VideoCapture(CAMERA_DEVICE_ID)
60+
# set resolution to 320x240 to reduce latency
61+
cap.set(3, IMAGE_WIDTH)
62+
cap.set(4, IMAGE_HEIGHT)
5163

5264
# Loop to continuously get images
5365
while True:
@@ -56,7 +68,10 @@ def visualize_fps(image, fps: int):
5668
start_time = time.time()
5769

5870
# Read the frames from a camera
59-
_, frame = cap.read()
71+
if IS_RASPI_CAMERA:
72+
frame = cap.capture_array()
73+
else:
74+
_, frame = cap.read()
6075

6176
# show image
6277
cv2.imshow('frame', visualize_fps(frame, fps))
@@ -78,4 +93,4 @@ def visualize_fps(image, fps: int):
7893
finally:
7994
# Clean up and exit the program
8095
cv2.destroyAllWindows()
81-
cap.release()
96+
cap.close() if IS_RASPI_CAMERA else cap.release()
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import cv2
2+
import numpy as np
3+
import time
4+
from picamera2 import Picamera2
5+
6+
7+
def visualize_fps(image, fps: int):
8+
if len(np.shape(image)) < 3:
9+
text_color = (255, 255, 255) # white
10+
else:
11+
text_color = (0, 255, 0) # green
12+
row_size = 20 # pixels
13+
left_margin = 24 # pixels
14+
15+
font_size = 1
16+
font_thickness = 1
17+
18+
# Draw the FPS counter
19+
fps_text = 'FPS = {:.1f}'.format(fps)
20+
text_location = (left_margin, row_size)
21+
cv2.putText(image, fps_text, text_location, cv2.FONT_HERSHEY_PLAIN,
22+
font_size, text_color, font_thickness)
23+
24+
return image
25+
26+
# Load the cascade
27+
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
28+
29+
# Initialize Picamera2 and configure the camera
30+
picam2 = Picamera2()
31+
picam2.configure(picam2.create_preview_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
32+
picam2.start()
33+
fps = 0
34+
35+
while True:
36+
# ----------------------------------------------------------------------
37+
# record start time
38+
start_time = time.time()
39+
# Read the frame
40+
img = picam2.capture_array()
41+
# Convert to grayscale
42+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
43+
# Detect the faces
44+
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
45+
# Draw the rectangle around each face
46+
for (x, y, w, h) in faces:
47+
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
48+
# Display
49+
cv2.imshow('img', visualize_fps(img, fps))
50+
# ----------------------------------------------------------------------
51+
# record end time
52+
end_time = time.time()
53+
# calculate FPS
54+
seconds = end_time - start_time
55+
fps = 1.0 / seconds
56+
print("Estimated fps:{0:0.1f}".format(fps))
57+
# Stop if escape key is pressed
58+
k = cv2.waitKey(30) & 0xff
59+
if k==27:
60+
break
61+
62+
# Release the VideoCapture object
63+
picam2.close()
64+
cv2.destroyAllWindows()
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
#!/usr/bin/python3
2+
3+
# ------------------------------------------------------------------------------
4+
# Detect any motion in the frame.
5+
# ------------------------------------------------------------------------------
6+
# automaticdai
7+
# YF Robotics Labrotary
8+
# Instagram: yfrobotics
9+
# Twitter: @yfrobotics
10+
# Website: https://www.yfrl.org
11+
# --------------------------------------------#!/usr/bin/python3
12+
13+
# ------------------------------------------------------------------------------
14+
# Detect any motion in the frame.
15+
# ------------------------------------------------------------------------------
16+
# automaticdai
17+
# YF Robotics Labrotary
18+
# Instagram: yfrobotics
19+
# Twitter: @yfrobotics
20+
# Website: https://www.yfrl.org
21+
# ------------------------------------------------------------------------------
22+
23+
import cv2
24+
import time
25+
import numpy as np
26+
27+
from picamera2 import Picamera2
28+
29+
MOTION_BLUR = True
30+
31+
cnt_frame = 0
32+
fps = 0
33+
34+
# Initialize Picamera2 and configure the camera
35+
picam2 = Picamera2()
36+
picam2.configure(picam2.create_preview_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
37+
picam2.start()
38+
39+
def mse(image_a, image_b):
40+
# the 'Mean Squared Error' between the two images is the
41+
# sum of the squared difference between the two images;
42+
# NOTE: the two images must have the same dimension
43+
err = np.sum((image_a.astype("float") - image_b.astype("float")) ** 2)
44+
err /= float(image_a.shape[0] * image_a.shape[1])
45+
46+
# return the MSE, the lower the error, the more "similar"
47+
# the two images are
48+
return err
49+
50+
51+
def visualize_fps(image, fps: int):
52+
if len(np.shape(image)) < 3:
53+
text_color = (255, 255, 255) # white
54+
else:
55+
text_color = (0, 255, 0) # green
56+
row_size = 20 # pixels
57+
left_margin = 24 # pixels
58+
59+
font_size = 1
60+
font_thickness = 1
61+
62+
# Draw the FPS counter
63+
fps_text = 'FPS = {:.1f}'.format(fps)
64+
text_location = (left_margin, row_size)
65+
cv2.putText(image, fps_text, text_location, cv2.FONT_HERSHEY_PLAIN,
66+
font_size, text_color, font_thickness)
67+
68+
return image
69+
70+
71+
if __name__ == "__main__":
72+
try:
73+
74+
while True:
75+
# ----------------------------------------------------------------------
76+
# record start time
77+
start_time = time.time()
78+
# ----------------------------------------------------------------------
79+
# Read the frames from a camera
80+
frame_raw = picam2.capture_array()
81+
82+
if MOTION_BLUR:
83+
# Denoise the frame
84+
frame = cv2.GaussianBlur(frame_raw, (3,3),0)
85+
else:
86+
frame = frame_raw
87+
88+
# Convert to gray image
89+
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
90+
91+
# Find edges
92+
edges = cv2.Canny(frame_gray,100,200)
93+
94+
# Show the original and processed image
95+
cv2.imshow('gray', visualize_fps(frame_gray, fps))
96+
cv2.imshow('edge', visualize_fps(edges, fps))
97+
98+
# Calculate MSE
99+
if cnt_frame > 0:
100+
if mse(frame_gray, frame_gray_p) > 100:
101+
print('Frame{0}: Motion Detected!'.format(cnt_frame))
102+
103+
# ----------------------------------------------------------------------
104+
# record end time
105+
end_time = time.time()
106+
107+
# calculate FPS
108+
seconds = end_time - start_time
109+
fps = 1.0 / seconds
110+
print("Estimated fps:{0:0.1f}".format(fps));
111+
112+
cnt_frame = cnt_frame + 1
113+
edges_p = edges
114+
frame_gray_p = frame_gray
115+
# ----------------------------------------------------------------------
116+
117+
# if key pressed is 'Esc' then exit the loop
118+
if cv2.waitKey(1)== 27:
119+
break
120+
except Exception as e:
121+
print(e)
122+
finally:
123+
# Clean up and exit the program
124+
cv2.destroyAllWindows()
125+
picam2.close()

0 commit comments

Comments
 (0)