Here’s a common question I get asked on the PyImageSearch blog:
How do I make a Python + OpenCV script start as soon as my system boots up?
There are many ways to accomplish. By my favorite is to use crontab and the @reboot option.
The main reason I like this method so much is because crontab exists on nearly every Unix machine (plus, crontab is a really neat utility that I think everyone should have at least some experience with).
It doesn’t matter if you’re on Raspbian, Linux, or OSX — crontab is likely to be installed on your system.
In the remainder of this blog post, I’ll demonstrate how to utilize crontab to start a Python + OpenCV script when your system boots up.
Looking for the source code to this post?
Jump Right To The Downloads SectionRunning a Python + OpenCV script on reboot
As I mentioned in the introduction to this blog post, we’ll be using crontab to launch a script on system reboot.
I’ll be using my Raspberry Pi to accomplish, but the same general instructions apply for other Linux distributions and OSX as well — all you need to do is change the paths to your scripts.
An example application
In last week’s post, I demonstrated how to create an “alarm” program that detects this green ball in a video stream:
If this green ball is detected, an alarm is raised by activating a buzzer and lighting up an LED on the TrafficHAT module (which is connected to a Raspberry Pi):
An example of the “activated alarm” can be seen below:
Here we can see the green ball is in view of the camera. Our program is able to detect the presence of the ball, light up an LED on the board, and if there was sound, you could hear the buzzer going off as well.
Today, we are going to take this example alarm program and modify it so that it can be started automatically when the Raspberry Pi boots up — we will not have to manually execute any command to start our alarm program.
Creating the launcher
Before we can execute our Python script on reboot, we first need to create a shell script that performs two important tasks:
- (Optional) Accesses our Python virtual environment. I’ve marked this step as optional only because in some cases, you may not be using a Python virtual environment. But if you’ve followed any of the OpenCV install tutorials on this blog, then this step is not optional since your OpenCV bindings are stored in a virtual environment.
- Executes our Python script. This is where all the action happens. We need to (1) change directory to where our Python script lives and (2) execute it.
Accomplishing both these tasks is actually quite simple.
Below I have included the contents of my on_reboot.sh
shell script which I have placed in /home/pi/pi-reboot
:
#!/bin/bash source /home/pi/.profile workon cv cd /home/pi/pi-reboot python pi_reboot_alarm.py
When we reboot our Pi, the on_reboot.sh
script will be running as the root user (provided that you edit the root crontab, of course; which we’ll cover in the next section).
However, we first need to access the cv
virtual environment (or whatever Python virtual environment you are using), so we’ll call source /home/pi/.profile
to setup the virtual environment scripts, followed by workon cv
to drop us into the cv
environment.
Note: To learn about Python virtual environments, please refer to this post.
After we have setup our environment, we change directory to /home/pi/pi-reboot
, which is where I have stored the pi_reboot_alarm.py
script.
Finally, we are ready to execute pi_reboot_alarm.py
— executing this script will be done within the cv
virtual environment (thanks to the source
and workon
commands).
Note: Again, make sure you have read both the accessing RPi.GPIO and GPIO Zero with OpenCV post and the OpenCV, RPi.GPIO, and GPIO Zero on the Raspberry Pi post before continuing with this tutorial. Both of these posts contain important information on configuring your development environment and installing required Python packages.
After adding these lines to to your on_reboot.sh
, save the file and then. Then, to make it executable, you’ll need to chmod
it:
$ chmod +x on_reboot.sh
After changing the permissions of the file to executable, you’re ready to move on to the next step!
Updating crontab
Now that we have defined the on_reboot.sh
shell script, let’s update the crontab to call it on system reboot.
Simply start by executing the following command to edit the root user’s crontab:
$ sudo crontab -e
This command should bring up the crontab file, which should look something like this:
You should then enter the following lines at the bottom of the file:
@reboot /home/pi/pi-reboot/on_reboot.sh
This command instructs the system to execute the on_reboot.sh
script whenever our system is rebooted.
Note: You can obviously replace the path to on_reboot.sh
with your own shell script.
Once you have finished editing the crontab, save the file and exit the editor — the changes to crontab will be automatically applied. Then at next reboot, the on_reboot.sh
script will be automatically executed.
Creating our Python script
The contents of pi_reboot_alarm.py
are near identical to last week’s blog post on OpenCV, RPi.GPIO, and GPIO Zero on the Raspberry Pi, but I’ve included the contents of the script as a matter of completeness:
# import the necessary packages from imutils.video import VideoStream from gpiozero import TrafficHat import argparse import datetime import logging import imutils import time import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--picamera", type=int, default=-1, help="whether or not the Raspberry Pi camera should be used") ap.add_argument("-l", "--log", type=str, default="log.txt", help="path to output log file") args = vars(ap.parse_args())
Lines 2-9 handle importing our required Python packages. We’ll be using VideoStream
to seamlessly access either the Raspberry Pi camera module or USB camera module. The TrafficHat
class from gpiozero
will allow us to easily manipulate the TrafficHAT board. And the imutils library will be used for some OpenCV convenience functions.
If you don’t already have imutils
installed, let pip
install it for you:
$ pip install imutils
Lines 12-17 parse our command line arguments. The first argument, --picamera
is used to indicate whether or not the Raspberry Pi camera module should be used. By default, a USB webcam is assumed to be connected to the Pi. But if you want to use the Raspberry Pi camera module instead, simply supply --picamera 1
as a command line argument. The second switch, --log
, is used to control the path to the output log file which can be used for debugging.
Our next code block handles performing a series of initializations, including accessing the VideoStream
class and setting up the TrafficHat
module:
# open the logging file logging.basicConfig(filename=args["log"], level=logging.DEBUG) # initialize the video stream and allow the cammera sensor to # warmup logging.info("[{}] waiting for camera to warmup".format( datetime.datetime.now())) vs = VideoStream(usePiCamera=args["picamera"] > 0).start() time.sleep(2.0) # define the lower and upper boundaries of the "green" # ball in the HSV color space greenLower = (29, 86, 6) greenUpper = (64, 255, 255) # initialize the TrafficHat and whether or not the LED is on th = TrafficHat() ledOn = False
We can now move on to the main video processing pipeline of our script, where we read frames from the VideoStream
and process each of them, looking for a green ball:
# loop over the frames from the video stream while True: # grab the next frame from the video stream, resize the # frame, and convert it to the HSV color space frame = vs.read() frame = imutils.resize(frame, width=500) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # construct a mask for the color "green", then perform # a series of dilations and erosions to remove any small # blobs left in the mask mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) center = None
If we find the green ball, then we’ll buzz the buzzer and light up the green LED on the TrafficHAT:
# only proceed if at least one contour was found if len(cnts) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the radius meets a minimum size if radius > 10: # draw the circle and centroid on the frame cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv2.circle(frame, center, 5, (0, 0, 255), -1) # if the led is not already on, raise an alarm and # turn the LED on if not ledOn: logging.info("[{}] alarm ON".format( datetime.datetime.now())) th.buzzer.blink(0.1, 0.1, 10, background=True) th.lights.green.on() ledOn = True
Finally, if the green ball is not found, we’ll turn off the LED on the TrafficHAT:
# if the ball is not detected, turn off the LED elif ledOn: logging.info("[{}] alarm OFF".format( datetime.datetime.now())) th.lights.green.off() ledOn = False # do a bit of cleanup logging.info("[{}] cleaning up".format( datetime.datetime.now())) cv2.destroyAllWindows() vs.stop()
Again, for a more comprehensive review of this code, please refer to last week’s blog post.
Assuming you’ve read through last week’s post, you might notice an interesting modification — I’ve removed the call to cv2.imshow
, which is used to display output frames to our screen.
Why would I do this?
Mainly because our pi_reboot_alarm.py
script is meant to run in the background when our Pi is rebooted — the output is never meant to be displayed to our screen. All we care about is the alarm being properly raised if the green ball enters our video stream.
Furthermore, removing calls to cv2.imshow
reduces I/O latency, thereby allowing our Python script to run faster and process frames quicker (you can read more about I/O latency related to video streams in this post).
Executing a Python script at reboot
All that’s left to do now is test our crontab installation by rebooting our system. To restart my Raspberry Pi, I execute the following command:
$ sudo reboot
And as the following video demonstrates, as soon as my Pi boots up, the on_reboot.sh
shell script is called, thereby executing the pi_reboot_alarm.py
Python program and arming the alarm:
You can see from the following screenshot that once the green ball enters the view of the camera, the green LED of the TrafficHAT is illuminated:
And if you watch the video above, you can also hear the buzzer going off at the same time.
What's next? I recommend PyImageSearch University.
30+ total classes • 39h 44m video • Last updated: 12/2021
★★★★★ 4.84 (128 Ratings) • 3,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 30+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 30+ Certificates of Completion
- ✓ 39h 44m on-demand video
- ✓ Brand new courses released every month, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 500+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this blog post, I demonstrated how to use crontab to launch a Python + OpenCV script on reboot.
To accomplish this task, I utilized my Raspberry Pi; however, crontab is installed on nearly all Unix machines, so no matter if you’re on Linux or OSX, crontab is likely available for you to use.
Anyway, I hope you enjoyed this series of blog posts on utilizing the Raspberry Pi, OpenCV, and GPIO libraries. If you would like to see more blog posts about these topics, please leave a comment in the comments section at the bottom of this post.
And before you go, don’t forget to enter your email address in the form below to be notified when new blog posts are published!
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Atomek
That’s a useful tutorial, exactly what I needed right now. Great job!
More articles on interfacing between OpenCV and GPIO would be welcome, e.g. working with a DC+Stepper Motor HAT which moves the camera to follow an object.
Thanks!
Adrian Rosebrock
Thanks Atomek! I don’t have a stepper motor/servo yet, that’s something I need to invest in. Do you have one that you’re already using that you can recommend?
Atomek
I’m using a 2 axis motor from car mirror. It’s supposed to required 12V but I’m running it straight from Raspberry’s USB 5V. It’s slower but that allows for more precision.
http://www.ebay.co.uk/itm/261770579933
Adrian Rosebrock
Thanks for sharing 🙂
Josh
Just a heads up, @reboot isn’t terribly reliable. Setting up an init script/systemd unit file (depending on OS version). Would be a much more reliable way of accomplishing what you’re looking for. With systemd you’d also get the free benefit of process monitoring and sane logging.
Adrian Rosebrock
I (personally) don’t like systemd for this type of thing as this GIF jokes about. Upstart for Debian-based systems is also a good option.
Lukas
Hi,
I wanted to share also a good option to start something on boot, called “supervisor” (install via “apt-get supervisor”). Very handy since you can start, stop, restart and get status of your running apps. I am using it for my RPI projects 😉
Adrian Rosebrock
Thanks for sharing Lukas!
Kerem
Hi Adrian, for some reason I’m getting the following error when I manually call the on-reboot.sh to test it :
/home/pi/pi-reboot/on_reboot.sh: line 3: workon: command not found
my script is still running but it is not executing inside the virtual environment.
When I type workon cv at the command prompt it runs without a problem and I can get into the virtual env.
Any ideas what I might be missing here? Thanks much for all your guidance.
Adrian Rosebrock
It sounds like your
.profile
file is not beingsource
‘d before executingworkon
. Without runningsource /home/pi/.profile
first, your system paths will not be setup correctly to find theworkon
command.Kerem
Hi Adrian, thanks for your kind reply. This is why I’m all confused.
On the command prompt I use the following commands
pi@Rpi3:~ $ source ~/.profile
pi@Rpi3:~ $ workon cv
(cv) pi@Rpi3:~ $ deactivate
and as you will note I am able to get into the virtualenv without any trouble and then deactivate to come back out.
My on_reboot.sh contents look like the following :
#!/bin/bash
source ~/.profile
workon cv
but when I execute this I get the workon: command not found error.
So if I understand this correctly what you are suggesting is that the call to source ~/.profile in my script is not doing its job and as a result my system paths are not setup for the script to find the workon command.
Funny thing is, as soon as I terminate the script and type workon at command prompt I am able to get workon to run.
Hope this provides some hints as to what might be wrong in my environment. Many thanks for your amazing support.
Adrian Rosebrock
On reboot, your script is being executed as the root user, not the pi user. Therefore, you need to supply the full path to the
.profile
file:source /home/pi/.profile
Hai
You can add your script executable command to the bottom of .bashrc that will run your script every time you log in.
Make sure you are in the pi folder:
$ cd ~
Create a file and write a script to run in the file:
$ sudo nano superscript
Save and exit: Ctrl+X, Y, Enter
Open up .bashrc for configuration:
$ sudo nano .bashrc
Scroll down to the bottom and add the line: ./superscript
Save and exit: Ctrl+X, Y, Enter
If you are looking for a solution that works on bootup to the console, take a look at this link. Basic rundown:
Create a file for your startup script and write your script in the file:
$ sudo nano /etc/init.d/superscript
Save and exit: Ctrl+X, Y, Enter
Make the script executable:
$ sudo chmod 755 /etc/init.d/superscript
Register script to be run at startup:
$ sudo update-rc.d superscript defaults
If you want a script to run when you boot into the LXDE environment, you could take a look at this Raspberry Pi forum post:
Navigate to etc/xdg/lxsession/LXDE-pi
Open the autostart file in that folder:
$ sudo nano autostart
Add @midori on a new line. If you want to run something like a python script, put something like @python mypython.py on a new line. Running a script file would be @./superscript, but for some reason the script runs in an infinite loop (perhaps this will stop that).
Save and exit: Ctrl+X, Y, Enter
Restart your Raspberry Pi into the LXDE environment.
http://raspberrypi.stackexchange.com/questions/8734/execute-script-on-start-up
Adrian Rosebrock
Awesome, thanks so much for sharing Hai!
Jeck
I have the same prob as kerem. I followed your installation tutorial for pi 3 + opencv + python. I ran the on_reboot.sh in root in order to emulate what happens during boot. The results were the same as kerem said. It seems we are only able to go to our opencv virtual env after logging in (not in root). How are you able to go to your virtual environment while still in root?
PS. I also made a log directory so i can see errors during boot. The resulting error messages were the same as the one generated by the one above
Adrian Rosebrock
You can still access your Python virtual environment while in the root account. For example, if I wanted to launch a root shell and access my virtual environment from the “pi” account, all I would need to do is:
And from there, you can access the
cv
virtual environment as the root user. You can apply the same technique to your shell scripts that are launched on boot as well.Jeck
thanks for the reply. but unfortunately it didn’t work. once I typed workon cv. an error has occured.
ERROR: Environment ‘cv’ does not exist. Create it with ‘mkvirtualenv cv’.
root@raspberrypi:/home/pi#
Adrian Rosebrock
If the
cv
virtual environment doesn’t exist, then you may have installed OpenCV without Python virtual environments. That’s totally okay, but you’ll need to manually debug the issue. Please note that I can only support OpenCV install questions if you followed one of my OpenCV install tutorials.Hai
Run it In terminal : bash yourscript.sh
Adrian Rosebrock
If the script is already executable, you could also do:
$ ./yourscript.sh
ghanendra
Hey Adrian how to open tkinter gui on startup?? . I ‘m using vncserver to execute the script
Adrian Rosebrock
So your goal is to boot up your Pi, have it automatically launch the GUI interface, and then at the same time open your TKinter GUI script?
ghanendra
On boot up, Pi launches with GUI interface, only how to open Tkinter GUI script?
Adrian Rosebrock
I personally haven’t tried this before, but I imagine you could accomplish this by editing your .xinitrc file.
Emrah
Dear Adrian
I had started learning OpenCV with your book about 2 years ago. Now, It is quite amazing to see how you constantly enhanced your courses/blog posts according to industry and our needs over the past years.
And again, you sensed our needs quite accurately by publishing this crontab tutorial.
Adrian Rosebrock
Thank you for the kind words Emrah! 🙂
ishant
hello adrian
i followed your steps, i checked it after bash filename.sh but after reboot its not running
Adrian Rosebrock
Hey Ishant — it’s hard to tell what the exact issue may be on your machine without having access to it. Take a look at my reply to “Luis Lopez” above for suggestions on how to debug the script.
luis lopez
hey adrian, first of all thank you for all the help you provide us, i have learned a lot from you and i just want you to know that you are a great teacher and person.
Now, I have a problem with one script, I did everything you said in this lesson and it works just fine when I reboot except with one script that does nothing after the reboot reboot, it’s the only one that does this and the only difference between this script and the others is that I use the skfuzzy library, do you think this has something to do? or how can i check whats wrong?.
Again thanks for everything.
Adrian Rosebrock
I would suggest inserting as many logging statements into your script as possible. Have the script write to a file you can monitor (like using print statements to debug). You may have forgotten to install skfuzzy into your virtual environment and the script could be throwing an error when trying to import it (hence the script not running). That’s just a best guess though.
Dua
Hello, and thank you a lot for this lesson.
I have done exactly what you have instructed in this tutorial, and when I tested the on_reboot.sh file from the terminal it worked out perfectly. But unfortunately when I reboot the Pi nothing happens. I added the line on crontab file and everything, but still nothing is happening when I reboot. Do you have any idea why is this happening?
thank you,
Adrian Rosebrock
It’s hard to say without having physical access to your machine. I would suggest inserting some
echo
calls that log to file insideon_reboot.sh
to help determine ifon_reboot.sh
is actually being called. There might be an error in your crontab entry.ANAS MUBARAK
Gtk-WARNING **; cannot open display : on log while running above
Adrian Rosebrock
It sounds like you’re trying to use
cv2.imshow
in your Python reboot script. This will not work since the script is running in the background. Remove the call tocv2.imshow
and your script should work.Melrick Nicolas
hi adrian , i made a cronlog to know the what is happening and i found out tha the error says
(opencv:523):gtk -warning **:can not open display:
what do you think happen?
tnx for your tutorial
Adrian Rosebrock
Are you calling
cv2.imshow
from your cronjob? That won’t work. The cronjob runs in the background and does not have access to the display.Nikita
is there any other method we can use for display it on window, after i boot the system
sahil
will this work for home surveillance system shown in other tutorial?
do i need to remove cv2.imshow part ?
and how to wait before pi is connected to internet after rebooting for dropbox access?
plz reply..
Adrian Rosebrock
Yes, make sure you remove the
cv2.imshow
calls so that script simply runs in the background.sahil
will it be connected to internet before execution of code or show error?
Adrian Rosebrock
That is hard to say as you cannot guarantee an internet connection (invalid WiFi password, network down, etc.) You would want to add extra logic to ensure your Raspberry Pi is connected to the internet if that is possible. The easiest way to do this would be via a shell script rather than trying to code it in Python.
sahil
thank you sir
David Steele
Adrian,
Thanks for the good advice. I was using the cv2.imshow in the python script that was called on reboot and I was getting the GTK Error. I need to have the image display to work on reboot. Please advise where I can find the procedure to display the cv2.imshow image after reboot.
Adrian Rosebrock
A Python script executed in the background does not have access to the window manager, hence the GTK error. I would suggest updating your Pi such that the
pi
user is automatically logged into the Raspberry Pi and the window manager started. From there you should be able to update your~/.profile
file to automatically launch the script.Nikita
can you please explain this i really want to start the video streaming after the boot process.
albert
Hi Adrian, my script works/environment works normally when manually run(im using your preinstalled py3cv3 environment). But when i try and run it with crontab with @reboot it throws the error of
Traceback (most recent call last):
File “reboot.py”, line 2, in
from imutils.video import VideoStream
ImportError: No module named imutils.video
the environment i’m using has imultils installed and i can run it manually but am not sure why it’s not running with @reboot??
Any hints you have would be really good, thanks!
albert
Thanks Adrian for the tutorials, really detailed and useful!
Just to add an alternative method, i had trouble starting the virtual environment with the workon command, with many imports like cv2 or imutils not being found. I managed to get around this using this startup script instead:
#!/bin/bash
. /home/pi/.virtualenvs/py3cv3/bin/activate
cd /home/pi/Scripts/
python videoSave.py >> /home/pi/on-reboot/feedback.log 2>&1
deactivate
cd /home/pi
Hope this is helpful
Adrian Rosebrock
Thank you for sharing Albert!
William
my crontab is empty. I have been trying to run @reboot python /home/pi/reboot8.py. This script looks for an input on GPIO to reboot the Rpi in case of lost remote control ie., other side of the planet. I placed that statement in my crontab anyway but doesn’t take. Your instruction go from optional cv to running a cv script anyway. A little guidance please, old brains aren’t as quick the youngins.
Thanks
Adrian Rosebrock
Hi William — thanks for the comment, although I’m not sure what your exact question is? It sounds like you are trying to edit your crontab file but it is always empty? Are you making sure to save and exit the editor?
valica
I have exactly the same issue.
I added traces and yes, on_reboot is fired at boot.
The problem is that .profile is not OK when running it as root.
For example executing sudo /bin/bash && source ~/.profile
and then workon cv
There is an error telling:
ERROR: Environment ‘cv’ does not exist. Create it with ‘mkvirtualenv cv’
I followed completely your user guide for installing python and opencv3.
I tried to copy all .profile content in on_reboot.sh and that’s the same.
I think the virtualenv is not OK when running as root but I don’t know why.
Adrian Rosebrock
Hi Valica, instead of trying to use the “workon” command on boot try specifying the full path to the Python virtual environment binary instead:
$ ./home/pi/.virtualenvs/cv/bin/python your_script.py
That should resolve the issue.
Anirban
it says permission denied
Anirban
Sorry , My bad !! It’s still not activating virtual environment
Adrian Rosebrock
You do not have to activate the Python virtual environment provided you supply the full path to the Python interpreter inside the virtual environment.
valica
Hi Adrian,
Indeed, this is the solution I’ve used.
However I’m wondering why virtualenv is not OK when running as root…
Another potential solution that I will check is to use cron as a different user than root. Normally this should run OK when setting the virtualenv.
Sang
I want to display use cv2.imshow. How to do?
Adrian Rosebrock
Please take a look at my reply to “ghanendra”.
Marius
Hi Adrian
I tried everything to make this work on pi3 with stretch but no luck at all. In the end I did this:
sudo nano /etc/systemd/system/yourservice.service
Put this inside
[Install]
WantedBy=multi-user.target
[Unit]
Description=Example service
Wants=network-online.target
After=network-online.target
[Service]
User=youruser
Group=yourgroup
WorkingDirectory=/home/pi/yourdirectory
ExecStart=/path/to/your/script.py
ExecStartPre=/bin/sleep 10
Type=simple
[Timer]
OnStartupSec=25
Then ran these commands
sudo systemctl enable yourname
sudo systemctl start yourname
sudo systemctl status yourname
Marius
I forgot to mention that you use the full path to your virtual env python bin when calling the script. Just as you mentioned a couple of posts up.
Jack Boyd
I ended up with a similar solution to @Marius but used the following script inside the new service to initialize the virtual environment:
#!/bin/bash
HOME=/home/pi
VENVDIR=$HOME/.virtualenvs/py3cv3
BINDIR=$HOME/SmartSecurityCamera
cd $BINDIR
source $VENVDIR/bin/activate
python $BINDIR/main2.py
Credits to @dbsahu who described the auto boot solution for a nice SmartSecurityCamera solution using CV by HackerHouse. https://www.hackster.io/hackerhouse/smart-security-camera-90d7bd
Adrian Rosebrock
Thank you for sharing, Jack!
Pari
Hi Adrian,
I tried so many different approaches using such your tutorial, Jack Boyd’s comment, your reply to Valica and so many others such like myfile.service in /lib/systemd/system/myfile.service and rc.local in /etc/rc.local but still I am not succeed 🙁 and when I run sh on_reboot.sh I get the following error:
source: not found
workon cv : not found
and when I replace it with the path ./home/pi/.virtualenvs/cv/bin/activate : not found
import error: No module named cv 2.
I have installed python 2.7+openCV using your tutorial on my Pi 3 model B with Stretch OS.
I am looking forward to get a solution.
I am thankful to you and your support to us.
Adrian Rosebrock
Are you calling just a single Python script on reboot? If so you can skip the “source” and “workon” commands and supply the full path to the Python interpreter:
/home/pi/.virtualenvs/cv/bin/python your_script.py
Pari
Thank you for your response!
No. There are multiple files connected to my script.py. I have a system that recognise the images and stores the unknown images. This is the source code I am using: https://github.com/OmkarPathak/Smart-Surveillance-System-using-Raspberry-Pi
However I have modified it somehow and I am running only the recognize-people on bootup. I have followed your instruction and removed cv2.imshow and the code is fully functional using terminal but not bootup.
Adrian Rosebrock
I would suggest create an entirely separate test Python script that logs a line to file (such as the timestamp). Focus on getting the script to run on boot first, then worry about running the Python + OpenCV script on boot. Right now there are too many variables. Try to eliminate some.
Tony
Instead of saying “sh script”, use “bash script”. Sh and bash are not the same program.
Pari
Thank you very much for your comment.
I worked for me but I had to add another command line in the crontab as follow:
@reboot sudo sh -x /home/pi/myFolder/on_reboot.sh
Anirban
Hi Adrian , I have done everything that you have told here. Whenever I run the on_reboot.sh on terminal it runs perfectly but on reboot its not working. I can’t seem to find the problem !! Everything is alright with shell script , it works perfectly. I have checked the path that have been given to the crontab file, it’s also right, but the script won’t start at startup.
I am working on raspberry pi 3 with raspbian stretch os.
Adrian Rosebrock
How are you validating that it’s not starting? Keep in mind that crontab will run the script in the background, not the foreground.
Anders Weile
In case anyone is interested; I too had problems, executing the script at startup, due to a permission problem.
In crontab, this solved it:
@reboot sudo su – pi bash -c ‘/home/pi/start.sh’
I use it, as root-user, to run the startup-script as user “pi”
tee
I tried to apply this on drowsiness detection on raspberry pi i follow everything and works fine when i run it on command line. However when I reboot the pi the script it is not working.
Adrian Rosebrock
Are you using a Python virtual environment? If so, you may be forgetting to access it via the “workon” command before executing your script.
Greg
Thank you very much!
Adrian Rosebrock
You are welcome, Greg!
sajid rehman
adrian you should make a video for that beacuse i try like 1000 times but on every reboot nothing happen plz help i did every single step
Adrian Rosebrock
To help you debug the process I suggest:
1. Trying to run your command from your terminal to ensure it works as you think it does
2. Create a simple Python script that writes some text to a file (so you can debug that the script is actually running on reboot)
3. From there, actually try to insert your Python + OpenCV script.
Peter Bahrs
On a raspberry pi with raspbian stretch, this will autostart a python 3.6 opencv 3 program that uses cv2.imshow. This is with a raspbian and Pixel.
Edit /home/pi/.config/lxsession/LXDE-pi/autostart
Add a line
@/home/pi/run_stuff.sh
Create a file:
/home/pi/run_stuff.sh
Add your commands to run, for example:
echo “starting run_stuff.sh” > ~/out.txt
export DISPLAY=:0.0
cd /home/pi/myprograms
py myopencvprog.py -d 4 &
echo “finished run_stuff.sh” >> ~/out.txt
then change permissions:
chmod 755 run_stuff.sh
then reboot. This will autostart your opencv python program when you reboot. However, I don’t think it will restart if it crashes. Need cron or something.
You can omit the echo statements – just for tracing
You can change to whatever directory you need and invoke your own programs and arguments.
Adrian Rosebrock
WOW! Thank you so much for sharing this, Peter!!
Brad
THANK-YOU PETER! I made the following (minor) change to line 4 in the .sh:
python3 myopencvprog.py -d 4 &
and needed “sudo” before chmod: sudo chmod 755 run_stuff.sh
I was also successfully able to call this .sh from crontab
Vasyl Hiruk
I have fulfilled the procedure described in this chapter, however without success. Only after I have accomplished what was written in the comment by Peter Bahrs dated December 1, 2018, the scripts on reboot started running automatically.
Thank you Peter and Adrian too !
Mr.chuot
hi, all.
I don’t automatically run an Opencv application on boot
Please, help me.
Adrian Rosebrock
Are you trying to run the app in the background (via a cronjob) or launch it via the GUI?
hongyu
Hello,
thank you for sharing. But I have a problem. I made the shell file, the virtual environment and python script run with no problem when I try it. But when I reboot, the indicator light of camera was activated for 2 seconds, then crash out. The code was not run and cpu utilization was not changed. I tried systemd and it had the same problem. Any idea what happened?
Adrian Rosebrock
It sounds like the script is erroring out for some reason. Try redirecting the stddout and stderr output (when running the Python script) to a file so you can debug.
jaydeep
I was also facing “workon” command not found issue and below code worked for me
#!/bin/bash
source /home/pi/.profile
workon cv
cd /home/pi/pi-reboot
python pi_reboot_alarm.py
Luis C.
Hey Adrian,
First of all, thanks for this tutorial and all of the other setup tutorials for RBPi 4 and OpenCV.
So I’m also having the “workon: command not found” issue. I looked at some of the replies you posted to other people’s same issue, but none have worked. I made sure to source /home/pi/.profile so I’m not sure what could be the issue, unless there is something missing there.
Adrian Rosebrock
Instead of trying to “source” the file, instead supply the full path to the Python binary in the virtual environment:
$ /home/pi/.virtualenvs/your_env_name/bin/python your_script.py