Daveyman123 Daveyman123 - 5 days ago 4
Python Question

openCV and filenames in python

anybody familiar with openCV know how to make it so the output is a different file each time. OR how to make it so the video appends to the original one.

here is the code I am working with

import RPi.GPIO as GPIO
import cv2
import numpy as np
import datetime
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN)
import os
# Setup the camera such that it closes
# when we are done with it.

os.chdir ("/home/pi/Videos")
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
while True:
if GPIO.input(11) == 1:
filename = datetime.datetime.now() .strftime ("%Y-%m-%d-%H.%M.%$
print("about to record")
out = cv2.VideoWriter('video.avi', fourcc, 20.0, (640,480))
ret, frame = cap.read()
if ret==True:
out.appendleft(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q') or GPIO.input(11) $
break
else:

break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()


thanks in advance for any and all help!

Answer

This function will store data in a progressive filename system

 from os  import path


def open_next_file(someData, template='incomingVideo{}.jpg'):
""" Creates a new file for storing new Firmware.
"""

## Store upto 100 file names 
for serial in range(100):
    if not path.exists(template.format(serial)):
        ## if file does not exist,
        ## enter data into the new file

        with open(template.format(serial), 'wb+') as f:
            f.write(someData)
        break

    else:
        ## if file already exists then,
        ## don't write on existing files
        pass

return template.format(serial)

you can call this function everytime you want to write a new data to a new file viz. incomingVideo1.jpg or incomingVideo2.jpg

You can change the parameters according your needs.

Example

newFile = open_next_file(someDat="Write this inside")
print(newFile)

gives result as incomingVideoX.jpg where x depends on range() function in the loop