Auto-launch openCV python script on boot using Raspberry pi - Buster

Aswinth Raj's picture

Offline

Joined: Aug 16, 2016

Replies: 953
Auto-launch openCV python script on boot using Raspberry pi - Buster
July 4, 2020 - 2:10pm

There are many ways to start a python script on boot and the processes is suppose to be very easy. Well! it is easy if your python code does not use OpenCV and GPIO pins. But if you have some kind of GUI then it is not possible to launch the script directly from the boot sequence without loading the Desktop.  What supposedly is to be a 2 minutes job took a lot many hours so I decided to write this post as a note for future self and also to others

Note: Python OpenCv scripts with image frames can be displayed only after the GUI (Desktop) loads up. It is not possible to launch it from a text console. The best way to launch an OpenCV project is from the LXTerminal by modifying the autostart file. Other methods will fail with import cv2 "no module found" error or with the failed to load X server. 

modify the autostart file by following the code for Buster OS

sudo nano /etc/xdg/lxsession/LXDE-pi/autostart 

For Jessie OS or below, the autostart file can be accessed with below link

sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart 

When you open the file you will see the below code already in it

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash

 

Add "@lxterminal -e python3 /home/pi/Desktop/test_pgm.py"  this line to the file. Make sure you have used the right path and program name. Mine is in desktop and the program name is test_pgm.py you can also choose between python2 or python3 here. Make sure you place it above the @xscreensaver line. So in the code your file should be something like this

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@lxterminal -e python3 /home/pi/Desktop/Athena.py
@xscreensaver -no-splash

Save the file with Ctrl+X and Y  and reboot the system with sudo reboot to check the results.

Tip: The autostart file runs everytime you log into pi. So for testing the auto-launch code, you don't have to reboot every time, just log out and log-in and the autostart will get executed. 

 

 

 

Sourav Gupta's picture

Offline

Joined: Feb 12, 2018

Replies: 220
Great
July 4, 2020 - 2:26pm

Thanks for sharing.

John_Kripto's picture

Offline

Joined: Aug 11, 2018

Replies: 36
Nice!
July 6, 2020 - 5:23pm

Worked for me, but I also had to add

#!/usr/bin/env python3

this line on top of my script. Not sure if it is mandatory but it sure wont hurt to add this 

Debasis Parida's picture

Offline

Joined: Aug 22, 2019

Replies: 120
Thanks for sharing
July 6, 2020 - 6:37pm

It was very essential. Thank you