I've written a Python script that collects video for a specific amount of time, while also showing a frame of the images being recorded. The script is intended to close at the conclusion of one video session and then immediately get restarted by a service file in /etc/systemd/system/videoPy.service.
[Unit]
Description = starts video recorder
After = multi-user.target
[Service]
Type = simple
ExecStart = /usr/bin/python3 /home/fred/videoPy.py
TimeoutStartSec = infinity
Restart = on-failure
RestartSec = 5
User = fred
Group = users
[Install]
WantedBy = multi-user.target
Python script is
#!/usr/bin/env python3
import cv2
import numpy as np
import time
# Create a VideoCapture object. Setting to "0" opens onboard camera. Using "2" connects to usb camera.
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if (cap.isOpened() == False):
print("Unable to read camera feed")
# defines video length
capture_duration = 10
# Default resolutions of the frame are obtained.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
frame_per_sec = int('10')
# PROBLEM MAY BE BELOW. Makes an empty .avi, and that is it.
out = cv2.VideoWriter('/home/fred/videoPy_output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), (frame_per_sec), (frame_width,frame_height))
# Captures video for specified amount of time
start_time = time.time()
while( int(time.time() - start_time) < capture_duration ):
ret, frame = cap.read()
if ret==True:
#frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
# Press Q on keyboard to stop recording
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# When everything done, release the video capture and video write objects
cap.release()
out.release()
# Closes all the frames
cv2.destroyAllWindows()
The Python script is in /home/fred/. When I open a terminal at that location and enter "python3 camera.py" it works great, a window pops up showing the camera image and a 10 second .avi file in /home/Fred/ is produced just as it should...however when I run "sudo systemctl enable cameraPy.service" followed by "service cameraPy start" there is no window popping up with the camera image, however .avi files are created every 10 seconds, but they has a size of zero and are malformed. Consequently, the service file does appears to be functioning.
Thoughts on this? I've reinstalled opencv-python, as well as time-python, and imutils via "pip install" with no luck. I suspect that the problem is related to when "cv2_videowriter" is called per comment above. Thanks in advance.