示例#1
0
 def __init__(self,
              filename,
              window="Input",
              nextModule=None,
              fourCC_str="XVID",
              fps=15,
              size=None,
              bw=False,
              no_annotations=False):
     '''
     Constructor
     @param filename: The full output filename. Include the extension, such as .avi.
     @param window: The window name to use when displaying this VSP's
     output. Specify None to suppress showing the output, but note that
     if you modify the current image with annotations, those will be
     persisted "downstream" to later processors.
     @param nextModule: A Video Stream Processor object that should be
     invoked on every frame after this processor has finished.
     @param fourCC_str:  The "Four CC" string that is used to specify the encoder.
     @param fps: Frames per second. Not all codecs allow you to specify arbitrary frame rates, however.
     @param size: A tuple (w,h) representing the size of the output frames.
     @param bw: Specify true if you wish for a black-and-white only output.
     @param no_annotations: set to True to output the original, non-annotated version of the image
     '''
     cvFourCC = cv.CV_FOURCC(*fourCC_str)
     if bw:
         colorFlag = cv.CV_LOAD_IMAGE_GRAYSCALE
     else:
         colorFlag = cv.CV_LOAD_IMAGE_UNCHANGED
     self._bw = bw
     self._out = cv.CreateVideoWriter(filename, cvFourCC, fps, size,
                                      colorFlag)
     self._no_annotations = no_annotations
     AbstractVSP.__init__(self, window=window, nextModule=nextModule)
示例#2
0
    def __init__(self):

        # Constants
        time_limit = 60
        index = 0
        file_dir = "data"
        vid_type = ".avi"
        vid_date = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        vid_file = "%s%s" % (vid_date, vid_type)
        vid_path = os.path.join(file_dir, vid_file)
        log_type = '.csv'
        log_file = "%s%s" % (vid_date, log_type)
        log_path = os.path.join(file_dir, log_file)
        fps = 25.0
        frame_size = (640, 480) 

        gps_device="/dev/ttyS0"
        gps_baud=38400

        # Initialize Video Capture
        try:
            self.camera = cv2.VideoCapture(index)
            print 'cam initialized'
        except:
            print 'Cam failed'
        time.sleep(1)

        # Initialize Video Writer
        try:
            self.vid_writer = cv2.VideoWriter(vid_path, cv.CV_FOURCC('M', 'J', 'P', 'G'), fps, frame_size, True)
            print "video initialized"
        except:
            print 'Video failed'

        # Initialize CSV file
        try:
            self.csvfile = open(log_path, 'w')
        except:
            print 'CSV failed'

        # Initialize GPS
        try:
            self.lat = 0.0
            self.lon = 0.0
            self.alt = 0.0
            self.speed = 0.0    
            #self.gps = serial.Serial(gps_device, gps_baud)
            #thread.start_new_thread(self.update_gps, ())
            print 'gps initialized'
        except Exception as e:
            print 'GPS failed %s' % str(e)

        # Initialize Controller
        try:        
            self.angle = 0
            self.encoder = 0
            self.controller = serial.Serial('/dev/ttyACM0', 9600, timeout=0.05)
            thread.start_new_thread(self.update_controller, ())
        except Exception as e:
            print 'GPS failed %s' % str(e)
示例#3
0
def copy_paste_video(video_in, video_out, start_frame = 0, total_frames = 0):
    (capt, frames_num, fps, frame_width, frame_height) = open_video2(video_in)
    vwriter = cv2.VideoWriter(video_out, cv.CV_FOURCC('P', 'I', 'M', '1'), \
                                   fps, (frame_width, frame_height), True)
    assert start_frame >= 0
    if total_frames == 0:
        total_frames = frames_num - start_frame
    if start_frame + total_frames > frames_num:
        total_frame = frames_num - start_frame
    
    print 'Copy pasting frames %d-%d (total %d) from %s to %s' % \
            (start_frame, start_frame + total_frames, total_frames, video_in, video_out)
    
    frame_i = 0
    while frame_i < start_frame:
        _ = capt.read()
        frame_i += 1
        #print 'Skipped frame %d out of %d' % (frame_i, start_frame)

    frame_i = 0
    while frame_i < total_frames:
        frame = capt.read()
        if frame[0]:
            vwriter.write(frame[1])
            #print 'Written frame %d out of %d' % (frame_i, total_frames)
        frame_i += 1
示例#4
0
def convert2vid(bdjoints, fimgs, fps, Vtype=0):

    # Vtype : 0 : color m, 1: depth ,2: body index
    if Vtype == 0:
        fsize = (1920, 1080)
        extname = ''
    elif Vtype == 1:
        fsize = (512, 424)
        extname = 'dp'
    else:
        fsize = (512, 424)
        extname = 'bdidx'

    #now = datetime.datetime.now()
    vid = 'kinect' + repr(now.month).zfill(2) + repr(now.day).zfill(2) + repr(
        now.hour).zfill(2) + repr(now.minute).zfill(2) + '_' + extname + '.avi'
    video = cv.CreateVideoWriter(vid, cv.CV_FOURCC('L', 'A', 'G', 'S'), fps,
                                 fsize, True)
    print 'making video .....'

    for i in fimgs:
        bitmap = cv.CreateImageHeader(fsize, cv.IPL_DEPTH_8U, 3)
        cv.SetData(bitmap, i.tostring(), i.dtype.itemsize * 3 * i.shape[1])
        cv.WriteFrame(video, bitmap)
    print 'there r total ' + repr(len(fimgs)) + ' frames'
    del video
示例#5
0
 def recordToggleRun(self, evt=None):
   """ Camera Recording on/off was toggled by user. """
   if not self.recordToggle.GetValue():
     if self._videoWriter!=None:
       del self._videoWriter
     self._videoWriter = None
     self.recordCombo.Enable(True)
   else:
     #if name is empty, generate a unique file name for the directory
     name = self.recordCombo.GetValue()
     if name=="":
       tag = 1
       name = "video"+str(tag)+".avi"
       while name in os.listdir(self._videoDir):
         tag += 1
         name = "video"+str(tag)+".avi"
       self.recordCombo.SetValue(name)
     if '.' not in name: #append .avi if no dot extension
       name += ".avi"
       self.recordCombo.SetValue(name)
     
     fileName = self._videoDir+name
     
     #Create a videoWriter to save processed camera inputs
     #CreateVideoWriter(filename, fourcc, fps, frame_size, is_color)
     self._videoWriter = cv.CreateVideoWriter(fileName, cv.CV_FOURCC('I','Y','U','V'), \
                                              15, self._networkSize, 0)
     self.recordCombo.Disable()
示例#6
0
文件: ocv.py 项目: NidayeCC/Pyocv
 def __init__(self,
              path,
              size,
              fourcc=cv.CV_FOURCC('M', 'J', 'P', 'G'),
              fps=30,
              color=1):
     """Create a new OpenCV Instance"""
     self.writer = cv.CreateVideoWriter(path, fourcc, fps, size, color)
示例#7
0
 def __init__(self, video_file="data/test_5/drone_eye.avi"):
     self.cap = cv2.VideoCapture(video_file)
     self.cap.set(cv.CV_CAP_PROP_FPS, 30)
     self.image_processing = ImageProcessing(area_treshold=300)
     self.writer = cv2.VideoWriter(filename="kalman_tracking5.avi", fps=30, frameSize=(
         320, 240), fourcc=cv.CV_FOURCC('M', 'J', 'P', 'G'))
     self.cam_altitude = []
     self.observations = []
示例#8
0
 def __init__(self, fps, size, thread):
     self.thread = None
     if os.path.exists(self.get_record_path()):
         self.video = cv2.VideoWriter(self.get_record_path() + "/" + self.get_file_name(), 
                     cv.CV_FOURCC('D','I','V','3'), fps, size, True)
         self.thread = thread
         thread.add_observer(self.thread_observer)
     else:
         print "Error: record path not available"
示例#9
0
def mergeImageFilesToVideo(directory, outputFile="merge.avi", resolution=None, recurse=False):
  """ 
  Scan all files present in the specified directory and sort 
  alphabetically. Look at each file in order and if the file has
  an image extension (bmp, jpg, png) supported by OpenCV, then open
  it and append the image to an output video file.  If the resolution
  parameter is None then set the output video resolution to be the
  resolution of the first image file detected and resize subsequent
  image files to this size.
  @param directory: absolute directory location to scan.
  @param outputFile: name of the output video file to create.
  @param resolution: the output resolution to use for the video, if
  None then auto-detect based on first read image file.
  @param recurse: if true then recurse into all subdirectories and perform
  the same task to create one video file per directory containing images.
  """
  print "Check Dir: ",directory
  if not os.path.isdir(directory):
    raise RuntimeError("The path is not a valid directory.")
  
  cvImg = None
  videoWriter = None
  
  for file in os.listdir(directory):
    absFile = directory+file
    #print absFile
    ex = file[-4:]
    if os.path.isdir(absFile):
      if recurse:
        mergeImageFilesToVideo(absFile+os.sep, recurse=True)
    
    elif ex==".bmp" or ex==".jpg" or ex==".png":
      img = cv.LoadImage(absFile, cv.CV_LOAD_IMAGE_GRAYSCALE)
      if img==None:
        continue
      
      #TODO: what is img set to if file is not valid image?  (None?)
      if resolution==None:
        resolution = (img.width, img.height)
      if resolution[0]<64 or resolution[1]<64:
        resolution = (64,64)
      if videoWriter==None:
        outDir = DESTDIR+directory[len(ROOTDIR):].replace(os.sep, "_")
        print outDir+outputFile
        videoWriter = cv.CreateVideoWriter(outDir+outputFile, cv.CV_FOURCC('I','Y','U','V'), \
                                           15, resolution, 0)
      if cvImg==None:
        cvImg = cv.CreateImage(resolution, cv.IPL_DEPTH_8U, 1)
      
      cv.Resize(img, cvImg)
      cv.WriteFrame(videoWriter, cvImg)
      
  if videoWriter!=None:
    del videoWriter
示例#10
0
def create_v(frames, path):
    #fourcc = cv2.VideoWriter_fourcc(*'XVID')
    '''fourcc = cv.CV_FOURCC('i','Y', 'U', 'V')
	frame=cv.LoadImage(path+"/"+frames[2])
	frame_size = cv.GetSize(frame)
	print "Video size: ", frame_size  
	out=cv2.VideoWriter('output.avi',fourcc,1.0,frame_size)
	for i in frames:
		path1=path+i
		print path1
		img=cv2.imread(path1)
		s="./output/"+i[:-4]+".png"
		print s
		cv2.imwrite(s,img)
		out.write(img)
	out.release()'''

    frame = cv.LoadImage(path + "/" + frames[2])
    print dir(frame)
    fps = 1.0  # so we need to hardcode the FPS
    print "Recording at: ", fps, " fps"

    frame_size = cv.GetSize(frame)
    print "Video size: ", frame_size
    CODEC = cv.CV_FOURCC('D', 'I', 'V', '3')  # MPEG 4.3
    # CODEC = cv.CV_FOURCC('M','P','4','2') # MPEG 4.2
    # CODEC = cv.CV_FOURCC('M','J','P','G') # Motion Jpeg
    # CODEC = cv.CV_FOURCC('U','2','6','3') # H263
    # CODEC = cv.CV_FOURCC('I','2','6','3') # H263I
    # CODEC = cv.CV_FOURCC('F','L','V','1') # FLV
    CODEC = cv.CV_FOURCC('P', 'I', 'M', '1')  # MPEG-1
    CODEC = cv.CV_FOURCC('D', 'I', 'V', 'X')  # MPEG-4 = MPEG-1

    writer = cv.CreateVideoWriter(path + "/out.avi", CODEC, fps, frame_size,
                                  True)
    for i in frames:

        path1 = path + "/" + i
        print path1
        img = cv.LoadImage(path1)
        cv.WriteFrame(writer, img)
示例#11
0
    def save_movie(self):
        """
        Creates a movie with all faces found in the inputs.
        Guy is skipped if no face is found.

        :param out_folder: the location where to save the output image.
        :type out_folder: string

        :param fps: the number of frames per second to be displayed in final video (3)
        :type fps: int
        """
        speedrate = self.face_params.speed
        if "win" in sys.platform:
            fourcc = cv.CV_FOURCC('C', 'V', 'I', 'D')
        else:  # some kind of Linux/Unix platform
            fourcc = cv.CV_FOURCC('F', 'M', 'P', '4')

        # Corrects frameSize to get a nice video output
        frameSize = self.resizes_for_video_codec(
        )  # Fixme : Put in global parameter
        # We have to resize the out_image to make them fit with the desired size
        corr_im = cv.CreateImage(frameSize, self.depth, self.nChannels)

        #frameSize = (652, 498)
        pace = ["slow", "normal", "fast"]
        my_video = cv.CreateVideoWriter(self.get_out_file(), fourcc,
                                        self.speed[speedrate], frameSize, 1)
        ii = 0
        for a_guy in self.guys:
            if self.run:
                ii += 1
                self.notify_progress("Saving frame", ii, self.number_guys())

                #self.console_logger.info("Saving frame %d / %d" % (ii, self.number_guys()))
                self.my_logger.info("Saving frame %d / %d" %
                                    (ii, self.number_guys()))
                out_im = self.prepare_image(a_guy)

                cv.Resize(out_im, corr_im, cv.CV_INTER_LINEAR)

                cv.WriteFrame(my_video, corr_im)
 def __init__(self,
              filename,
              filename_metadata,
              resolution,
              fps,
              codec,
              color=True,
              parent=None):
     QtCore.QObject.__init__(self, parent)
     self.filename_metadata = filename_metadata
     self.writer = cv2.VideoWriter(filename, cv.CV_FOURCC(*codec), int(fps),
                                   resolution, color)
示例#13
0
 def start_video_writer(self):
     self.writer = cv.CreateVideoWriter(
         self.filename,
         cv.CV_FOURCC('D', 'I', 'V', 'X'),
         #cv.CV_FOURCC('U','2','6','3'),
         #cv.CV_FOURCC('H','2','6','4'),
         self.framerate,
         self.cv_image_size,
     )
     if self.writer is None:
         raise IOError, 'unable to create video writer'
     self.recording = True
示例#14
0
def write_video(vid_arr, filename, fps=10, h5input=False, fourcc=None):
    """
  Writes video to the specified filename

  parameters:
  vid_arr: A numpy array, GPUArray or PitchArray representing the video
  filename: The output filename
  fps: The frame rate of the output video
       If not specified, will be set to 10.
  h5input: True if vid_arr is a filename of an h5 file containg the video.
            If not specified, will be set to False.
  fourcc: An integer representing the codec to be used for 
          the video file. Can be specified using cv.CV_FOURCC.
          If not specified, will default to DIVX.
  
  """

    if (not (CV_INSTALLED)):
        raise ImportError("Failure to load OpenCV.\n \t " \
                            "write_video requires: OpenCV\n")
    if (h5input):
        vid_arr = io.read_file(vid_arr)
    else:
        if PYCUDA:
            if vid_arr.__class__.__name__ in ["GPUArray", "PitchArray"]:
                vid_arr = vid_arr.get()
            elif vid_arr.__class__.__name__ != "ndarray":
                raise TypeError("Write video error: Unknown input type")
        elif vid_arr.__class__.__name__ != "ndarray":
            raise TypeError("Write video error: Unknown input type")

    height = vid_arr.shape[1]
    width = vid_arr.shape[2]
    if vid_arr.min() < 0:
        vid_arr = vid_arr - vid_arr.min()
    if vid_arr.max() > 1:
        vid_arr = vid_arr / vid_arr.max()
    if len(vid_arr.shape) == 3:
        temp = vid_arr
        vid_arr = np.zeros((temp.shape[0], height, width, 3))
        for i in range(3):
            vid_arr[:, :, :, i] = 255 * temp[:, :, :]
        del temp

    vid_arr = vid_arr.astype('uint8')

    if fourcc is None:
        fourcc = cv.CV_FOURCC('D', 'I', 'V', 'X')
    writer = cv.CreateVideoWriter(filename, fourcc, fps, (width, height), 1)

    for i in xrange(vid_arr.shape[0]):
        cv.WriteFrame(writer, array2cv(vid_arr[i, :, :, :]))
示例#15
0
    def __init__(self):

        # Constants
        index = 0
        terrain = raw_input("Enter terrain: ")
        file_dir = "data"
        vid_type = ".avi"
        vid_date = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        vid_file = "%s_%s%s" % (vid_date, terrain, vid_type)
        vid_path = os.path.join(file_dir, vid_file)
        log_type = '.csv'
        log_file = "%s %s%s" % (vid_date, terrain, log_type)
        log_path = os.path.join(file_dir, log_file)
        fps = 25.0
        frame_size = (640, 480)

        gps_device = "/dev/ttyS0"
        gps_baud = 38400

        # Initialize Video Capture
        try:
            self.camera = cv2.VideoCapture(index)
            print 'cam initialized'
        except:
            print 'Cam failed'

        # Initialize Video Writer
        try:
            self.vid_writer = cv2.VideoWriter(vid_path,
                                              cv.CV_FOURCC('M', 'J', 'P', 'G'),
                                              fps, frame_size, True)
            print "video initialized"
        except:
            print 'Video failed'

        # Initialize CSV file
        try:
            self.csvfile = open(log_path, 'w')
        except:
            print 'CSV failed'

        # Initialize GPS
        try:
            self.lat = 0.0
            self.lon = 0.0
            self.alt = 0.0
            self.speed = 0.0
            self.gps = serial.Serial(gps_device, gps_baud)
            thread.start_new_thread(self.update_gps, ())
            print 'gps initialized'
        except Exception as e:
            print 'GPS failed %s' % str(e)
示例#16
0
    def __init__(self,
                 infile=None,
                 outfile=None,
                 fourcc="XVID",
                 preview=False):
        Log.info("opening videoCapture")
        if infile:
            # capture from input file
            self.capture = cv2.VideoCapture(args.infile)
            if not self.capture.isOpened():
                raise Exception("Could not open input file: %s" % infile)
        else:
            # capture from default camera
            Log.info("connecting to camera")
            self.capture = cv2.VideoCapture(0)
            self.capture.set(cv.CV_CAP_PROP_FRAME_WIDTH, 340)
            self.capture.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 240)
            # self.capture.set(cv.CV_CAP_PROP_EXPOSURE, 80)
            # self.capture.set(cv.CV_CAP_PROP_CONTRAST, 200)
            # self.capture.set(cv.CV_CAP_PROP_FPS, 15)
            # self.capture.set(cv.CV_CAP_PROP_BRIGHTNESS, .5)
            if not self.capture.isOpened():
                raise Exception("Could not connect to camera.")

        Log.info("reading test frame")
        if not self.captureFrame():
            raise Exception("Could not read from video source.")

        self.width = np.size(self.currentFrame, 1)
        self.height = np.size(self.currentFrame, 0)
        Log.info("width: " + str(self.width))
        Log.info("height: " + str(self.height))

        # clear out test frame
        self.frameCount = 0
        self.currentFrame = None

        if outfile:
            Log.info("opening videoWriter")
            f = fourcc
            fourcc = cv.CV_FOURCC(f[0], f[1], f[2], f[3])
            self.writer = cv2.VideoWriter(outfile, fourcc, 10.0,
                                          (self.width, self.height))
        else:
            self.writer = None

        if preview:
            cv2.namedWindow("preview", cv2.WINDOW_NORMAL)
            self.preview = True
        else:
            self.preview = False
示例#17
0
def generateVideoClip(videoDir="./video/"):
  """ 
  Generate a simple example black and white video clip that can be used
  as input to the Camera Toolkit for performing basic experiments.
  By default the method is writing a video file consisting of a horizontal
  white line against a black background. The line moves from top to 
  bottom and back again 1 pixel at a time.
  The code can be edited by changing the looping parameters on line 46
  and what is painted per frame on line 53.
  @param videoDir: the directory the video will be created in.
  """
  suffix = "Rectangle17.avi" #edit this for different file names
  fileName = videoDir+suffix
  width = 80  #the Region prefers 80x60 resolution video frames
  height = 60
      
  #Create a videoWriter to use to write out the generated video file
  #Always use uncompressed YUV codec for universal playback
  #method doc: CreateVideoWriter(filename, fourcc, fps, frame_size, is_color)
  videoWriter = cv.CreateVideoWriter(fileName, cv.CV_FOURCC('I','Y','U','V'), \
                                     15, (width,height), 0)
  
  #Allocate a PIL image to paint into for each video frame
  vidFrame = Image.new('L', (width,height))
  
  print "writing video",fileName
  
  #Each pass in this loop will generate a subsequent video frame
  #For a horizontal line, loop from top to bottom, and back again
  for x in range(8,width-25):
    #for y in xrange(15,height-15):
    #for i in range(0,height)+range(height-2,-1,-1):
    #fill frame with black, then draw white lines/dots for the frame
    draw = ImageDraw.Draw(vidFrame)
    draw.rectangle((0,0, width,height), fill="black")
    
    #now that frame is black again, draw a white line in current position
    #draw.line((0,i,width,i), fill="white", width=1)
    draw.rectangle((x,x, x+17,x+17), outline="white")
    
    #we could do other things here instead, such as drawing points:
    #draw.point((x,y), fill="white")
    del draw #done performing drawing for this frame
    
    #now convert the PIL image into an OpenCV image and write to video
    cvImage = cv.CreateImageHeader(vidFrame.size, cv.IPL_DEPTH_8U, 1)
    cv.SetData(cvImage, vidFrame.tostring())
    cv.WriteFrame(videoWriter, cvImage)
    
  del videoWriter #close video stream when done to finish file
  return suffix #return fileName suffix as indicator of success
示例#18
0
 def Record_Button_Clicked(self):
     if (not self.ui.Record_Button.isFlat()):
         self.ui.Record_Button.setText("Parar")
         self.ui.Record_Button.setFlat(True)
         self._writer = cv.CreateVideoWriter(
             filename=("img/" + time.strftime("%H%M%S") + ".avi"),
             fourcc=cv.CV_FOURCC('X', 'V', 'I', 'D'),
             fps=2,
             frame_size=(640, 480),
             is_color=1)
     else:
         self.ui.Record_Button.setText("Gravar")
         self.ui.Record_Button.setFlat(False)
         cv.ReleaseVideoWriter(self._writer)
示例#19
0
def download_and_process_video(save_path, row):
    video_id = row['VideoID']
    video_path = row['video_path']
    full_path = os.path.join(save_path, video_path)
    if os.path.exists(full_path):
        return

    start = row['Start']
    end = row['End']

    print video_id

    if os.path.exists('tmp.mp4'):
        os.system('rm tmp.mp4')

    try:  # 다운로드 포기
        youtube = YouTube("https://www.youtube.com/watch?v=" + video_id)
    except:
        print "다운로드 포기"
        return

    youtube.set_filename('tmp')

    try:  # 360p로 받아보고 안되면 예외처리
        video = youtube.get('mp4', '360p')
    except:
        ipdb.set_trace()
    video.download('.')

    cap = cv2.VideoCapture('tmp.mp4')
    fps = cap.get(cv.CV_CAP_PROP_FPS)
    fourcc = int(cap.get(cv.CV_FOURCC(*'XVID')))
    w = int(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT))

    out = cv2.VideoWriter(full_path, fourcc, fps, (w, h))

    start_frame = int(fps * start)
    end_frame = int(fps * end)

    frame_count = 0
    while frame_count < end_frame:
        ret, frame = cap.read()
        frame_count += 1

        if frame_count >= start_frame:
            out.write(frame)

    cap.release()
    out.release()
示例#20
0
def imageProc(fname):
    capture = cv2.VideoCapture(fname)

    #initialize variables for HSV limits and blur radius:
    blurRad = 5  #image blur radius

    #load camera
    #print capture.get(cv.CV_CAP_PROP_FPS)
    frsize = (int(capture.get(cv.CV_CAP_PROP_FRAME_WIDTH)),
              int(capture.get(cv.CV_CAP_PROP_FRAME_HEIGHT)))
    vidWriter = cv2.VideoWriter("stabilized.wmv",
                                cv.CV_FOURCC('M', 'J', 'P', 'G'),
                                capture.get(cv.CV_CAP_PROP_FPS), frsize)
    print vidWriter

    first = True
    shift = np.array([0, 0])
    while True:
        ret, img1 = capture.read()
        if ret:
            #read the camera image:
            if first:
                first = False
            else:
                imgNew = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
                imgLast = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

                #process frames

                #perform stabilization
                reet = cv2.phaseCorrelate(np.float32(imgNew),
                                          np.float32(imgLast))
                #lowpass filter
                alpha = 0.33333
                shift[0] = alpha * reet[0] + (1 - alpha) * shift[0]
                shift[1] = alpha * reet[1] + (1 - alpha) * shift[1]
                #shift = reet
                #shift the new image
                M = np.float32([[1, 0, shift[0]], [0, 1, shift[1]]])
                cols, rows = np.size(img1, axis=1), np.size(img1, axis=0)

                img3 = cv2.warpAffine(img2, M, (cols, rows))
                #export image
                vidWriter.write(img3)
            img2 = np.copy(img1)
        else:
            break

    if vidWriter.isOpened():
        vidWriter.release()
示例#21
0
def main():
    # source = pyglet.media.load('/media/ioana/Elements/media/_0nX-El-ySo_83_93.avi')
    source = pyglet.media.load('./bird.avi')
    frame1 = source.get_next_video_frame()
    frame2 = source.get_next_video_frame()
    frame3 = source.get_next_video_frame()
    video_id = 'mv89psg6zh4'
    full_path = './test.avi'
    start = 33
    end = 46

    if os.path.exists('tmp.mp4'):
        os.system('rm tmp.mp4')

    youtube = YouTube("https://www.youtube.com/watch?v=" + video_id)
    youtube.set_filename('tmp')

    video = youtube.get('mp4', '360p')

    video.download('.')

    cap = cv2.VideoCapture('tmp.mp4')
    fps = cap.get(cv.CV_CAP_PROP_FPS)
    fourcc = int(cap.get(cv.CV_FOURCC(*'XVID')))
    w = int(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT))

    out = cv2.VideoWriter(full_path, fourcc, fps, (w, h))

    start_frame = int(fps * start)
    end_frame = int(fps * end)

    frame_count = 0
    while frame_count < end_frame:
        ret, frame = cap.read()
        frame_count += 1

        if frame_count >= start_frame:
            out.write(frame)

    cap2 = cv2.VideoCapture(full_path)
    ret, frame = cap2.read()

    if ret is False:
        print "ret is False"
    else:
        print "ret is True"
示例#22
0
 def convert2othvid(self, string, imgs):
     now = datetime.datetime.now()
     vid = string + repr(now.month).zfill(2) + repr(
         now.day).zfill(2) + repr(now.hour).zfill(2) + repr(
             now.minute).zfill(2) + '.avi'
     video = cv.CreateVideoWriter(vid, cv.CV_FOURCC('L', 'A', 'G', 'S'),
                                  fps, (512, 424), True)
     #st = time.clock()
     #pdb.set_trace()
     print 'making video .....'
     for i in imgs:
         bitmap = cv.CreateImageHeader((512, 424), cv.IPL_DEPTH_8U, 3)
         cv.SetData(bitmap, i.tostring(), i.dtype.itemsize * 3 * i.shape[1])
         cv.WriteFrame(video, bitmap)
     #print time.clock()-st
     print 'there r total ' + repr(len(fimgs)) + ' frames'
     del video
示例#23
0
def find_fish(file_name,num_filters,input_file):
  finder = FishFinder(file_name,num_filters) 
  capture_file = cv.CreateFileCapture(input_file)
  output_file = get_output_name(input_file)


  loop = True
  frame = cv.QueryFrame(capture_file)
  video_writer = cv.CreateVideoWriter(output_file,cv.CV_FOURCC('P','I','M','1'),27.96,cv.GetSize(frame),1)
  while(loop):
    if (frame == None): print "no frame"; exit()

    #annotated_frame = finder.find_fish(frame)
    annotated_frame = finder.get_annotated_image(frame)
   
    cv.WriteFrame(video_writer,annotated_frame)#cvHelper.gray_colour_image(annotated_frame)) 
    frame = cv.QueryFrame(capture_file)
示例#24
0
    def __init__(self, width, height, source, threshold):
        self.width = width
        self.height = height
        self.threshold = threshold
        self.fourcc = cv.CV_FOURCC('M', 'J', 'P', 'G')
        self.capture_data = False

        self.cap = cv2.VideoCapture(source)
        self.cap.set(cv.CV_CAP_PROP_FRAME_WIDTH, 320)
        self.cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 240)

        self.fx = width / 320.0
        self.fy = height / 240.0

        self.heading = 0.0

        if self.capture_data:
            self.writer = cv2.VideoWriter('log.avi', self.fourcc, 6,
                                          (self.width, self.height))
示例#25
0
文件: write_cv.py 项目: zoginni/helit
    def nextFrame(self):
        if self.writer == None:
            four_cv = cv.CV_FOURCC(self.codec[0], self.codec[1], self.codec[2],
                                   self.codec[3])
            self.writer = cv.CreateVideoWriter(self.fn, four_cv, self.fps(),
                                               (self.width(), self.height()),
                                               1)

        frame = self.video.fetch(self.channel)
        mode = self.video.outputMode(self.channel)

        frame = (frame * 255.0).astype(numpy.uint8)
        if mode == MODE_RGB:
            out = array2cv(frame[:, :, ::-1])
        elif mode == MODE_FLOAT:
            out = array2cv(frame)
        else:
            raise Exception('Unsuported mode for WriteCV')

        cv.WriteFrame(self.writer, out)
        return True
示例#26
0
    def handle_recording_cmd(self, req):
        """
        Handles avi recording commands - starts and stops avi recording.
        """
        with self.lock:

            if self.cv_image_size is None:
                # If we don't have and image yet - we can't get started, return fail.
                return RecordingCmdResponse(False)

            self.filename = req.filename
            self.frame_rate = req.frame_rate
            command = req.command.lower()

            if command == 'start':
                # Get start time and create video writer
                self.writer = cv.CreateVideoWriter(
                    self.filename,
                    cv.CV_FOURCC('D', 'I', 'V', 'X'),
                    self.frame_rate,
                    self.cv_image_size,
                )

                if self.writer is None:
                    response = False
                else:
                    response = True
                    self.start_t = rospy.get_time()
                    self.frame_count = 0
                    self.done = False
                    self.recording_message = 'recording'

            elif command == 'stop':
                self.done = True
                del self.writer
                self.writer = None
                self.recording_message = 'stopped'
                response = True

            return RecordingCmdResponse(response)
示例#27
0
def make_video(outfile, results, names, colour, thickness):
    vw = cv2.VideoWriter(outfile, cv.CV_FOURCC('M','J','P','G'), 15, (640,480), 1)
    ri = 0
    for d in video_dirs:
        for n in xrange(1,6):
            vc, _ = open_benchmark(d, n)
            
            fi = 0
            while True:
                succ, img = vc.read()
                if not succ: break
                
                for name in names:
                    draw_region(img, results[name][ri][fi], colour[name], thickness[name])
                cv2.imshow("replay", img)
                cv2.waitKey(1)
                vw.write(img)
                fi += 1
                
            ri += 1
    
                
示例#28
0
def get_video_writer(cam, video_file='video.avi'):
    """Show video of camera's frame buffer"""

    #Define the codec and create VideoWriter object
    #CODEC = cv.CV_FOURCC('D','I','V','3') # MPEG 4.3
    #CODEC = cv.CV_FOURCC('M','P','4','2') # MPEG 4.2
    CODEC = cv.CV_FOURCC('M', 'J', 'P', 'G')  # Motion Jpeg
    #CODEC = cv.CV_FOURCC('U','2','6','3') # H263
    #CODEC = cv.CV_FOURCC('I','2','6','3') # H263I
    #CODEC = cv.CV_FOURCC('F','L','V','1') # FLV
    #CODEC = cv.CV_FOURCC('P','I','M','1') # MPEG-1
    #CODEC = cv.CV_FOURCC('D','I','V','X') # MPEG-4 = MPEG-1
    #CODEC=-1

    # Initialize the video writer to write the file
    writer = cv2.VideoWriter(
        video_file,  # Filename
        CODEC,  # Codec for compression
        cam.frame_rate,  # Frames per second
        cam.frame_resolution,  # Width / Height tuple
        False  # Color flag
    )
    return writer
示例#29
0
    def run(self, start=0):
        cv2.namedWindow("vis")
        cv2.setMouseCallback("vis", self.click_handler)
        if self.output_file != None:
            vw = cv2.VideoWriter(self.output_file,
                                 cv.CV_FOURCC('M', 'J', 'P', 'G'), 15,
                                 (800, 600), 1)
        active_trackers = []
        self.time = start
        while self.time < len(self.images):
            if not self.paused:
                img = self.images[self.time]
                gray_img = to_grayscale(img)

                to_remove = []
                for (t, end_time) in active_trackers:
                    if end_time == self.time: to_remove.append((t, end_time))
                    else: t.update(gray_img)
                for e in to_remove:
                    active_trackers.remove(e)

                for s in self.schedule:
                    if s.start_time == self.time:
                        tracker = self.tracker_maker()
                        tracker.initialize(gray_img, s.region)
                        active_trackers.append((tracker, s.end_time))

                self.time += 1

            annotated_img = img.copy()
            for (t, end_time) in active_trackers:
                draw_region(annotated_img, t.get_region(), (0, 255, 0), 2)

            cv2.imshow("vis", annotated_img)
            if self.output_file != None: vw.write(annotated_img)
            cv2.waitKey(1)
        cv2.destroyAllWindows()
示例#30
0
 def convert2vid(self, bdjoints):
     import datetime
     now = datetime.datetime.now()
     vid = 'kinect' + repr(now.month).zfill(2) + repr(
         now.day).zfill(2) + repr(now.hour).zfill(2) + repr(
             now.minute).zfill(2) + '.avi'
     video = cv.CreateVideoWriter(vid, cv.CV_FOURCC('L', 'A', 'G', 'S'),
                                  fps, (1920, 1080), True)
     #st = time.clock()
     #pdb.set_trace()
     print 'making video .....'
     for i in fimgs:
         bitmap = cv.CreateImageHeader((1920, 1080), cv.IPL_DEPTH_8U, 3)
         cv.SetData(bitmap, i.tostring(), i.dtype.itemsize * 3 * i.shape[1])
         cv.WriteFrame(video, bitmap)
     #print time.clock()-st
     print 'there r total ' + repr(len(fimgs)) + ' frames'
     del video
     cPickle.dump(
         bdjoints,
         file(
             'bodyjoints' + repr(now.month).zfill(2) +
             repr(now.day).zfill(2) + repr(now.hour).zfill(2) +
             repr(now.minute).zfill(2) + '.pkl', 'wb'))