Esempio n. 1
0
    def addFrame(self, img):
        '''
        @param img: A pyvision img to write out to the video.        
        '''
        if self._no_annotations:
            img2 = img
        else:
            img2 = pv.Image(img.asAnnotated())

        if self._bw:
            cv.WriteFrame(self._out, img2.asOpenCVBW())
        else:
            cv.WriteFrame(self._out, img2.asOpenCV())
Esempio n. 2
0
    def image_handler(self, data):
        """
        Writes frames to avi file.
        """
        if self.framerate is not None:
            # Convert to opencv image and then to ipl_image
            cv_image = self.bridge.imgmsg_to_cv(data, 'bgr8')
            ipl_image = cv.GetImage(cv_image)

            cv_image_size = cv.GetSize(cv_image)
            if self.frame_count == 0:
                self.cv_image_size = cv_image_size
                self.start_video_writer()

            if cv_image_size != self.cv_image_size:
                # Abort recording - image size changed.
                pass

            if self.recording:
                # Write video frame
                cv.WriteFrame(self.writer, ipl_image)
                self.frame_count += 1
        else:
            stamp = data.header.stamp
            if self.last_stamp is not None:
                diff_stamp = stamp - self.last_stamp
                dt = diff_stamp.to_sec()
                self.framerate = 1 / dt
            self.last_stamp = stamp
Esempio n. 3
0
    def image_handler(self, data):
        """
        Writes frames to avi file.
        """
        self.current_t = rospy.get_time()

        # Convert to opencv image and then to ipl_image
        cv_image = self.bridge.imgmsg_to_cv(data, 'bgr8')
        ipl_image = cv.GetImage(cv_image)

        with self.lock:
            if self.cv_image_size == None:
                self.cv_image_size = cv.GetSize(cv_image)

        if not self.done:

            # Write video frame
            cv.WriteFrame(self.writer, ipl_image)

            # Update times and frame count - these are used elsewhere so we
            # need the lock
            with self.lock:
                self.frame_count += 1
                self.progress_t = self.current_t - self.start_t

        # Publish progress message
        with self.lock:
            self.progress_msg.frame_count = self.frame_count
            self.progress_msg.progress_t = self.progress_t
            self.progress_msg.recording_message = self.recording_message
        self.progress_pub.publish(self.progress_msg)
Esempio n. 4
0
 def write_frame(self, img):
     """
     Write a frame to our video
     """
     self.frame_num += 1
     # cv.SaveImage("testimage%d.jpg" % self.frame_num, img)
     cv.WriteFrame(self._vidWriter, img)
Esempio n. 5
0
def VideoStream():
    """
	VideoStream should probably be updated to 
	utilized the cv2 python wrapper for opencv
	If you're having problems, remember to check the camera index, fps
	"""
    global Finished
    #display live video
    cv.NamedWindow("Badass video window", cv.CV_WINDOW_AUTOSIZE)
    #peripheral devices begin at > 0
    global camera_index
    capture = cv.CaptureFromCAM(camera_index)
    frame = cv.QueryFrame(capture)
    writer = cv.CreateVideoWriter(
        "Stream.avi", 0, 20, cv.GetSize(frame),
        1)  #"filename", codec,fps, frame_size, is_color=true
    #isight can't handle 30 fps so changed it to 15
    print "Calling thread at: ", time.time()
    Thread(target=AudioStream).start()
    i = 1
    while True:
        print "Recording Video Frame: ", i, " At: ", time.time()
        frame = cv.QueryFrame(capture)
        cv.WriteFrame(writer, frame)
        cv.ShowImage("Badass video window", frame)
        k = cv.WaitKey(10)  #milliseconds
        i += 1
        if k == 0x1b:  #ESC
            print 'ESC pressed. Exiting ... Time is: ', time.time()
            break
    Finished = True
    cv.DestroyWindow("Baddass video window")
    sys.exit(1)
    return
Esempio n. 6
0
 def Cam_Video(self):
     # Recebe uma imagem e manda mostrar na tela
     Actions.Receive_File()
     if (self.ui.Record_Button.isFlat()):
         frame = cv.LoadImage("img/img.jpg")
         cv.WriteFrame(self._writer, frame)
     self.Image_Show("img/img.jpg")
Esempio n. 7
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
Esempio n. 8
0
def write_send(camera, im, writer, s):
    try:
        # print "Sending %f " % time.time()
        s.send(('%f ' % time.time()).encode('latin-1'))
    except:
        pass
    cv.WriteFrame(writer, im)
Esempio n. 9
0
def DisplayWriteFrame(image):
    cv.ShowImage('Image_Window', image)

    i = 0
    while i < 15:
        cv.WriteFrame(writer, image)
        i += 1

    cv.WaitKey(1000)
Esempio n. 10
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
Esempio n. 11
0
 def write(self, image):
     """
     Write frame.
     
     cv_image (IplImage): Destination image.
     """
     if not self.writer:
         if not self.size:
             self.size = cv.GetSize(image)
         self.writer = cv.CreateVideoWriter(self.destination, self.codec, self.framerate, self.size, 1)
     cv.WriteFrame(self.writer, image);
     self.frame_num += 1
Esempio n. 12
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, :, :, :]))
Esempio n. 13
0
 def record(self):
     self.stan = 1
     while self.stan:
         original = cv.QueryFrame(self.capture)
         size = cv.GetSize(original)
         cv.ShowImage('Camera picture - PRESS ESC TO EXIT', original)
         k = cv.WaitKey(33)
         if k == 0x1b:  # ESC
             print 'ESC pressed. Exiting ...'
             break
         cv.WriteFrame(self.writer, original)
     #cv.ReleaseCapture(self.capture)
     cv.cvReleaseVideoWriter(self.writer)
Esempio n. 14
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
Esempio n. 15
0
File: vid.py Progetto: wy51r/kod
    def run(self):
        fps = 30
        frame = cv.QueryFrame(self.capture)
        frame_size = cv.GetSize(frame)
        writer = cv.CreateVideoWriter('movie.avi',
                                      cv2.cv.CV_FOURCC('F', 'M', 'P', '4'),
                                      fps, frame_size)
        while True:
            frame = cv.QueryFrame(self.capture)
            cv.ShowImage("CamShiftDemo", frame)
            c = cv.WaitKey(7)
            cv.WriteFrame(writer, frame)
            if c == 27:
                break

        cv.ReleaseVideoWriter(writer)
Esempio n. 16
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)
Esempio n. 17
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
Esempio n. 18
0
    def find_position(self):
	print "Kinect is trying to find the image"
        (kinect_depth,_), (rgb,_) = get_depth(), get_video() 
        self.img = video_cv(rgb)
        depth_img = pretty_depth_cv(kinect_depth)
 
        position = self._get_pos(self.img)

        depth = self._get_depth(depth_img, debug=False)

        font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) 

        fps = 1/(time.time() - self.lasttime)
        s1 = "FPS:%.2f" % fps
        self.lasttime = time.time()
        cv.PutText(self.img,s1, (0,30),font, cv.CV_RGB(255, 0, 0))

        dt = "Depth: %d" % depth
        if position:
            pt = "Pos: X=%d Y=%d" % (position[0], position[1])
        else:
            pt = "Pos: N/A"
        cv.PutText(self.img, dt, (0,60),font, cv.CV_RGB(255, 0, 0))
        cv.PutText(self.img, pt, (0,90),font, cv.CV_RGB(255, 0, 0))

        offset = 120
        for t in self.text:
            cv.PutText(self.img, t, (0,offset),font, cv.CV_RGB(255, 0, 0))
            offset += 30

        cv.Circle(self.img, (self.sp[0], self.sp[1]) , 10, cv.CV_RGB(0, 255, 0), 1)

        cv.ShowImage('RGB', self.img)
        #cv.SaveImage('RGB-%d.png' % (time.time()*100), self.img)
        #cv.ShowImage('DEPTH', depth_img)
        cv.WriteFrame(self.writer, self.img)
        cv.WaitKey(5)

        #cv.ShowImage('depth_mask', depth_mask)
        try:
            return (position[0], position[1], depth)
        except:
            return (None, None, None)
Esempio n. 19
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)
Esempio n. 20
0
    def main_loop(self):
        presentation = []
        self.orig = cv.QueryFrame(self.capture)
        #cv.PyrDown( self.orig, self.small, 7 ) # CV_GAUSSIAN_5x5 = 7
        cv.Resize(self.orig, self.small)
        cv.CvtColor(self.small, self.bw, cv.CV_BGR2GRAY)
        cv.CvtColor(self.small, self.hsv, cv.CV_BGR2HSV)
        cv.Split(self.hsv, self.hue, self.sat, self.val, None)
        cv.Copy(self.small, self.visualize)
        presentation.append(self.visualize)
        # presentation.append(self.hue)
        # presentation.append(self.sat)

        face = self.find_face(self.small)

        if face:
            self.update_histogram(face)

        bp = self.backproject()

        scaled = self.scale(bp)
        # presentation.append(scaled)

        th = self.threshold(scaled)
        # presentation.append(th)

        morphed = self.morphology(th)

        cv.Zero(self.result)
        cv.Copy(self.small, self.result, morphed)
        contours = self.find_contours(morphed)
        self.draw_contours(self.result, contours)
        limbs = self.find_limbs(contours)
        presentation.append(self.result)

        # combine and show the results
        combined = self.combine_images(presentation)
        cv.ShowImage('Skin Detection', combined)

        if STORE:
            cv.WriteFrame(self.writer, self.combined)
Esempio n. 21
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)
Esempio n. 22
0
 def captureFromCamera(self):
   """ 
   Capture a live frame from the camera and perform motion processing
   on the acquired image.  If recording is enabled, also write the processed
   frame to an output video file. 
   """
   frame = cv.QueryFrame(self._capture) # Grab the frame from the capture
   if not frame:
     self.stopRun()
     return None
   
   frameOut = self.__processVideoFrame(frame)
   
   # Mirror if using camera, this is more intuitive for webcams
   frameOut = ImageOps.mirror(frameOut)
 
   if self._videoWriter: #if recording enabled, write out to the video file
     cvImage = Util.convertPILToCV(frameOut)
     cv.WriteFrame(self._videoWriter, cvImage)
   
   return frameOut
Esempio n. 23
0
    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
Esempio n. 24
0
    def image_handler(self,data): 
        """
        Writes frames to avi file.
        """
        self.current_t = rospy.get_time()

        # Convert to opencv image and then to ipl_image
        cv_image = self.bridge.imgmsg_to_cv(data,'bgr8')
        ipl_image = cv.GetImage(cv_image)

        with self.lock:
            if self.cv_image_size == None:
                self.cv_image_size = cv.GetSize(cv_image)

        if not self.done:

            # Write video frame
            cv.WriteFrame(self.writer,ipl_image)

            # Update times and frame count - these are used elsewhere so we 
            # need the lock
            with self.lock:
                self.frame_count += 1
                self.progress_t = self.current_t - self.start_t
                
                # Check to see if we are done recording - if so stop writing frames 
                if self.current_t >= self.start_t + self.record_t:
                    self.done = True
                    del self.writer
                    self.writer = None
                    self.recording_message = 'finished'
                    db_tools.set_bool(self.redis_db,'recording_flag',False)

        # Publish progress message
        with self.lock:
            self.progress_msg.frame_count = self.frame_count
            self.progress_msg.record_t = self.record_t
            self.progress_msg.progress_t = self.progress_t
            self.progress_msg.recording_message = self.recording_message
        self.progress_pub.publish(self.progress_msg)
Esempio n. 25
0
    def pipeline(self):
        presentation = []
        self.orig = self.source.grab_frame()
        cv.Resize(self.orig, self.small)

        size = self.smallsize

        # store the raw image
        presentation.append((self.small, 'raw'))

        self.motion = cv.CloneImage(self.small)

        # location of the thingy moving on the screen is defined by center
        center = self.process_motion(self.motion)

        # if an object is found draw the circle on the same location.
        if center != (-1, -1):
            cv.Circle(self.motion, center, cv.Round(30), cv.CV_RGB(0, 225, 0),
                      3, cv.CV_AA, 0)
        # store the picture
        presentation.append((self.motion, 'motion'))

        ####
        # processing of final image
        self.eye = cv.CloneImage(self.small)  # get a copy

        (r, color) = self.dejitter(center)
        cv.Circle(self.eye, self.old_center, cv.Round(r), color, 3, cv.CV_AA,
                  0)

        presentation.append((self.eye, 'final'))

        # combine and show the results
        combined = self.combine_images(presentation)
        cv.ShowImage('Motion detection', combined)

        if self.store:
            cv.WriteFrame(self.writer, self.combined)
Esempio n. 26
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'))
Esempio n. 27
0
HEIGHT = 480

import sys
import os
import cv

if len(sys.argv) != 4:
    print "use this te create movie of images\n"
    print "usage: %s <image folder> <output movie> <showtime>\n" % sys.argv[0]
    sys.exit(1)

image_folder = sys.argv[1]
output_movie = sys.argv[2]
showtime = int(sys.argv[3])

if not os.access(image_folder, os.X_OK):
    print "can't acess %s" % image_folder
    sys.exit(1)

writer = cv.CreateVideoWriter(output_movie, cv.CV_FOURCC('M', 'J', 'P', 'G'),
                              FPS, (WIDTH, HEIGHT), True)
sized = cv.CreateImage((WIDTH, HEIGHT), cv.IPL_DEPTH_8U, 3)

for f in [x for x in os.listdir(image_folder) if not x.startswith('.')]:
    p = os.path.join(image_folder, f)
    print "loading", p
    frame = cv.LoadImage(p)
    cv.Resize(frame, sized)
    for i in range(FPS * showtime):
        print cv.WriteFrame(writer, sized)
Esempio n. 28
0
                    python_opencv_modulu.ResetImageROI(goruntu_yakala)
                    toplam.update()
                    if toplam.y + toplam.height >= cerceve_boyutu[1]:
                        toplam.aktif = False
                        sayi -= 1
                else:
                    toplam.y = 0
                    toplam.x = rasgele.randint(
                        0, cerceve_boyutu[0] - logo_bau.width)
                    if toplam.hiz[1] < 15:
                        toplam.hiz = (0, toplam.hiz[1] + 1)
                    skor += sayi

    python_opencv_modulu.PutText(goruntu_yakala, "Skorunuz : %d" % skor,
                                 (10, cerceve_boyutu[1] - 10), yazi_tipi,
                                 python_opencv_modulu.RGB(0, 0, 0))
    python_opencv_modulu.ShowImage("Python - Bahçeşehir University Game",
                                   cerceve)
    if yazdir_goruntuyu:
        python_opencv_modulu.WriteFrame(video_yazdir, goruntu_yakala)
    python_opencv_modulu.ShowImage("Python - Bahçeşehir University Game",
                                   goruntu_yakala)
    previous = python_opencv_modulu.CloneImage(current)
    beklenen_anahtar = anahtar.WaitKey(2)
    if beklenen_anahtar == 27:
        break

    gecikme_zamani -= 1

print skor
Esempio n. 29
0
filename = "../data/output/weighted.avi"
# Codec is OS dependant.
# FIXME : Find an unified version
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')

fps = 5
frameSize = cv.GetSize(im1)
my_video = cv.CreateVideoWriter(filename, fourcc, fps, frameSize, 1)

num_inter_im = 10
step = float(1) / 10

for i in range(num_inter_im + 1):
    print i
    im3 = cv.CreateImage(cv.GetSize(im1), im1.depth, im1.nChannels)
    alpha = step * i
    beta = 1 - alpha
    gamma = 0
    cv.AddWeighted(im1, alpha, im2, beta, gamma, im3)
    cv.WriteFrame(my_video, im3)

# cv.NamedWindow("im3", cv.CV_WINDOW_NORMAL)
# cv.ResizeWindow("im3", 640, 480)
# cv.MoveWindow("im3", 640, 500)
# cv.ShowImage("im3", im3)

# cv.WaitKey(delay)
Esempio n. 30
0
    # Next open the file for output
    outStream = cv.CreateVideoWriter(
        outputFile, cv.CV_FOURCC('P', 'I', 'M', '1'), fps,
        (cv.GetCaptureProperty(inStream, cv.CV_CAP_PROP_FRAME_WIDTH),
         cv.GetCaptureProperty(inStream, cv.CV_CAP_PROP_FRAME_HEIGHT)),
        1)  # is_color

    curTime = 0
    cvFrame = cv.QueryFrame(inStream)
    while (cvFrame is not None):

        frame = np.asarray(cv.GetMat(cvFrame)).astype(np.float64) / 255.0
        motionExtractor.AddImage(frame, curTime)

        if (motionExtractor.RetreiveObjects() is not None
                and (curTime - motionExtractor.time() < 5.0 / fps)):
            # Create a new frame showing the objects in red
            outFrame = frame
            outFrame[:,:,2] = outFrame[:,:,2]*0.6 + 0.4 * \
                              motionExtractor.RetreiveObjects().ToBinaryImageMask().astype(np.float64)

            outFrame *= 255.0
            cv.WriteFrame(outStream,
                          cv.GetImage(cv.fromarray(frame.astype(np.uint8()))))

        cvFrame = cv.QueryFrame(inStream)
        curTime += 1.0 / fps

        print 'Processed %f seconds' % curTime