Пример #1
0
class AviWriter:
    def __init__(self,
                 fName,
                 size=None,
                 fps=25,
                 isColor=True,
                 fourcc=cv.CV_FOURCC(*'MJPG')):  #('X','V', 'I', 'D')):

        self.fileName = fName
        self.width = -1
        self.height = -1
        self.frames = 0
        self.fps = fps
        self.aviHandler = None
        self.fourcc = fourcc
        self.isColor = isColor
        self.size = size

    def __del__(self):
        self.clearAviHandler()

    def clearAviHandler(self):
        if self.aviHandler != None:
            self.aviHandler.release()
            self.aviHandler = None

    def getFileName(self):
        return self.fileName

    def getWidth(self):
        return self.width

    def getHeight(self):
        return self.height

    def getFrames(self):
        return self.frames

    def open(self, w, h):
        self.clearAviHandler()
        print(self.fileName)
        print(self.fourcc)
        print(self.fps)
        print(self.size)
        print(self.isColor)
        self.aviHandler = VideoWriter(self.fileName, self.fourcc, self.fps,
                                      (w, h), self.isColor)

    def addFrame(self, data):
        h, w, z = data.shape

        if self.aviHandler == None:
            self.open(w, h)

        if not self.aviHandler.isOpened():
            print("AviWriter file is not opened, cannot save!")
            return
        data = cvtColor(data, cv.CV_RGB2BGR)
        self.aviHandler.write(data)
Пример #2
0
def videoWriter(ofn, fourcccode, xypix, usecolor):
    """
    inputs
    ofn: string/Path output filename to write
    fourcccode: string with four character fourcc code e.g. 'FFV1'
    xypix: two-element tuple with x,y pixel count
    usecolor: bool color or bw
    """
    cc4 = fourcc(*fourcccode)

    print('saving to {} with {}'.format(ofn, fourcccode))

    hv = VideoWriter(ofn, cc4, fps=5, frameSize=xypix, isColor=usecolor)

    if not hv or not hv.isOpened():
        raise RuntimeError('trouble starting video {}'.format(ofn))

    return hv
Пример #3
0
    def as_video(self, pathname: str):
        if self.img_number is 0:
            print("Warning: no images into this TiffSequence.")
            print("Warning: cannot build a video from this image sequence.")
            return

        # Path security check
        if not path.exists(pathname):
            makedirs(pathname)

        # Save the current active image from the sequence.
        old = self.current()[0]

        # Now reset to 0
        self.active(0)

        # The whole video will have the same shape than
        # the first sequence image.
        idx, tif = self.current()
        _h, _w = tif.shape()

        # video name, based on the current timestamp.
        # output format is '.MKV'
        vname = pathname+str( time() )+".mkv"
        
        # Create a VideoWirter:
        # encoded using HFYU (Huffman Lossless Codec)
        # 25 frames/sec
        # Size( width, height )
        # False -> no color images.
        video = VideoWriter(
            vname, 
            VideoWriter_fourcc('H','F','Y','U'), 
            25.0, 
            (_w, _h), 
            False
        )

        # If the VideoWriter creation failed, exit.
        # e.g.:
        # HFYU codec is not present at runtime on the machine.
        if video.isOpened() is False:
            print("Video failed to build.")
            return
        
        # Remember that we alreay read the first sequence image.
        # During the process, 16-bits greyscale images
        # are converted to 8-bits.
        video.write( tif.to_8bits() )
        
        # Read the complete sequence.
        while idx+1 is not self.img_number:
            self.shift_right()
            idx, tif = self.current()
            video.write( tif.to_8bits() )

        # Close the VideoWriter
        video.release()

        # Put back the sequence in the way
        # it was before building video.
        self.active(old)
Пример #4
0
#dist = np.vectorize(dist_proto)

for i in range(0, FPS * seconds, 2):

    frame = np.zeros((height, width, 3), dtype=np.uint8)
    #frame = np.array(np.fromfunction(dist, (height, width, 3), dtype=np.uint8))
    print(frame.shape)
    terrain(frame)
    grass(frame)
    person(frame, (500, 250))

    video.write(frame)
video.release()

video = VideoCapture("noise.avi")
while video.isOpened():
    ret, frame = video.read()

    if not ret:
        break

    cv2.imshow("frame", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    time.sleep(5)

video.release()
cv2.destroyAllWindows()
Пример #5
0
def captureTStamp(files, duration, cod,  fps=0, verbose=True):
    '''
    guarda por un tiempo en minutos (duration) el video levantado desde la
    direccion indicada en el archvo indicado. tambíen archivos con los time
    stamps de cada frame.
    
    files = [ur, saveVideoFile, saveDateFile, saveMillisecondFile]
    duration = time in mintes
    cod = codec
    fps = frames per second for video to be saved
    verbose = print messages to screen
    
    si fpscam=0 trata de llerlo de la captura. para fe hay que especificarla
    
    para opencv '2.4.9.1'
    
    Examples
    --------
    
    from cameraUtils import captureTStamp
    
    # para la FE
    duration = 1 # in minutes
    files = ['rtsp://192.168.1.48/live.sdp',
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_tsFrame.txt"]
    fpsCam = 12
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fps=fpsCam)
    
    # %% para la PTZ
    duration = 0.2 # in minutes
    files = ["rtsp://192.168.1.49/live.sdp",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_tsFrame.txt"]  
    
    fpsCam = 20
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fpsCam)
    
    '''
    
    fcc = fourcc(cod[0],cod[1],cod[2],cod[3]) # Códec de video
    
    if verbose:
        print(files)
        print("Duration",duration,"minutes")
        print("fps",fps)
        print("codec",cod)
    
    # Inicializacion
    tFin = datetime.datetime.now() + datetime.timedelta(minutes=duration)
    
    ts = list()  # timestamp de la captura
    
    # abrir captura
    cap = VideoCapture(files[0])
    while not cap.isOpened():
        cap = VideoCapture(files[0])
    
    print("capture opened")
	# configurar writer
    w = int(cap.get(frame_width))
    h = int(cap.get(frame_height))
    if not fps:
        fps = cap.get(prop_fps)
    #para fe especificar los fps pq toma cualquier cosa con la propiedad
    
    out = VideoWriter(files[1], fcc, fps,( w, h), True)
    
    if verbose:
        print("capture open",cap.isOpened())
        print("frame size",w,h)
        print("output opened",out.isOpened())
    
    if not out.isOpened() or not cap.isOpened():
        out.release()
        cap.release()
        # exit function if unable to open cap or out
        return
    
    s0 = getsize(files[1]) # initial filesize before writing frame
    # Primera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("first frame captured")
    # Segunda captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("second frame captured")
    # Tercera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("third frame captured")
    
    s1 = getsize(files[1])  # size after saving 3 frames
    
    if s1==s0:
        out.release()
        cap.release()
        print("error when saving 3 frames, exiting")
        return 1 # error while saving first frame to file
    print(tFin)
    # loop
    while (t <= tFin):
        ret, frame = cap.read()
        
        if ret:
            t = datetime.datetime.now()
            ts.append(t)
            out.write(frame)
            if verbose:
                print(tFin,t)
                print("seconds elapsed",cap.get(pos_msec)/1000)
                print(frame.size)

    # end of loop
    
    # release and save
    out.release()
    cap.release()
    
    if verbose:
        print('loop exited, cap, out released, times saved to files')
        
    savetxt(files[2],ts, fmt= ["%s"])
    
    return 0  # success
Пример #6
0
def captureTStamp(files, duration, cod, fps=0, verbose=True):
    '''
    guarda por un tiempo en minutos (duration) el video levantado desde la
    direccion indicada en el archvo indicado. tambíen archivos con los time
    stamps de cada frame.
    
    files = [ur, saveVideoFile, saveDateFile, saveMillisecondFile]
    duration = time in mintes
    cod = codec
    fps = frames per second for video to be saved
    verbose = print messages to screen
    
    si fpscam=0 trata de llerlo de la captura. para fe hay que especificarla
    
    para opencv '2.4.9.1'
    
    Examples
    --------
    
    from cameraUtils import captureTStamp
    
    # para la FE
    duration = 1 # in minutes
    files = ['rtsp://192.168.1.48/live.sdp',
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_tsFrame.txt"]
    fpsCam = 12
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fps=fpsCam)
    
    # %% para la PTZ
    duration = 0.2 # in minutes
    files = ["rtsp://192.168.1.49/live.sdp",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_tsFrame.txt"]  
    
    fpsCam = 20
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fpsCam)
    
    '''

    fcc = fourcc(cod[0], cod[1], cod[2], cod[3])  # Códec de video

    if verbose:
        print(files)
        print("Duration", duration, "minutes")
        print("fps", fps)
        print("codec", cod)

    # Inicializacion
    tFin = datetime.datetime.now() + datetime.timedelta(minutes=duration)

    ts = list()  # timestamp de la captura

    # abrir captura
    cap = VideoCapture(files[0])
    while not cap.isOpened():
        cap = VideoCapture(files[0])

    print("capture opened")
    # configurar writer
    w = int(cap.get(frame_width))
    h = int(cap.get(frame_height))
    if not fps:
        fps = cap.get(prop_fps)
    #para fe especificar los fps pq toma cualquier cosa con la propiedad

    out = VideoWriter(files[1], fcc, fps, (w, h), True)

    if verbose:
        print("capture open", cap.isOpened())
        print("frame size", w, h)
        print("output opened", out.isOpened())

    if not out.isOpened() or not cap.isOpened():
        out.release()
        cap.release()
        # exit function if unable to open cap or out
        return

    s0 = getsize(files[1])  # initial filesize before writing frame
    # Primera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("first frame captured")
    # Segunda captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("second frame captured")
    # Tercera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("third frame captured")

    s1 = getsize(files[1])  # size after saving 3 frames

    if s1 == s0:
        out.release()
        cap.release()
        print("error when saving 3 frames, exiting")
        return 1  # error while saving first frame to file
    print(tFin)
    # loop
    while (t <= tFin):
        ret, frame = cap.read()

        if ret:
            t = datetime.datetime.now()
            ts.append(t)
            out.write(frame)
            if verbose:
                print(tFin, t)
                print("seconds elapsed", cap.get(pos_msec) / 1000)
                print(frame.size)

    # end of loop

    # release and save
    out.release()
    cap.release()

    if verbose:
        print('loop exited, cap, out released, times saved to files')

    savetxt(files[2], ts, fmt=["%s"])

    return 0  # success