Python cv2.CAP_PROP_POS_FRAMES Examples

The following are 30 code examples of cv2.CAP_PROP_POS_FRAMES(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: capture.py    From EdgeRealtimeVideoAnalytics with Apache License 2.0 7 votes vote down vote up
def __next__(self):
        self.count += 1

        # Respect FPS for files
        if self.isFile:
            delta = time.time() - self.ts
            self.sma.add(delta)
            time.sleep(max(0,(1.0 - self.sma.current*self.fps)/self.fps))
            self.ts = time.time()

        # Read image
        ret_val, img0 = self.cam.read()
        if not ret_val and self.isFile:
            self.cam.set(cv2.CAP_PROP_POS_FRAMES, 0)
            ret_val, img0 = self.cam.read()
        assert ret_val, 'Video Error'

        # Preprocess
        img = img0
        if not self.isFile:
            img = cv2.flip(img, 1)

        return self.count, img 
Example #2
Source File: visualizer.py    From higan with MIT License 7 votes vote down vote up
def read(self, position=None):
    """Reads a certain frame.

    NOTE: The returned frame is assumed to be with `RGB` channel order.

    Args:
      position: Optional. If set, the reader will read frames from the exact
        position. Otherwise, the reader will read next frames. (default: None)
    """
    if position is not None and position < self.length:
      self.video.set(cv2.CAP_PROP_POS_FRAMES, position)
      self.position = position

    success, frame = self.video.read()
    self.position = self.position + 1

    return frame[:, :, ::-1] if success else None 
Example #3
Source File: video.py    From videocr with MIT License 6 votes vote down vote up
def run_ocr(self, lang: str, time_start: str, time_end: str,
                conf_threshold: int, use_fullframe: bool) -> None:
        self.lang = lang
        self.use_fullframe = use_fullframe

        ocr_start = utils.get_frame_index(time_start, self.fps) if time_start else 0
        ocr_end = utils.get_frame_index(time_end, self.fps) if time_end else self.num_frames

        if ocr_end < ocr_start:
            raise ValueError('time_start is later than time_end')
        num_ocr_frames = ocr_end - ocr_start

        # get frames from ocr_start to ocr_end
        with Capture(self.path) as v, multiprocessing.Pool() as pool:
            v.set(cv2.CAP_PROP_POS_FRAMES, ocr_start)
            frames = (v.read()[1] for _ in range(num_ocr_frames))

            # perform ocr to frames in parallel
            it_ocr = pool.imap(self._image_to_data, frames, chunksize=10)
            self.pred_frames = [
                PredictedFrame(i + ocr_start, data, conf_threshold)
                for i, data in enumerate(it_ocr)
            ] 
Example #4
Source File: util.py    From smashscan with MIT License 6 votes vote down vote up
def show_frames(capture, frame_num_list, bbox_list=None, wait_flag=True):

    # Iterate through the frame_num_list, while using indexes for bboxes.
    for frame_index, frame_num in enumerate(frame_num_list):
        capture.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
        _, frame = capture.read()
        if bbox_list:
            frame = cv2.rectangle(frame, bbox_list[frame_index][0],
                bbox_list[frame_index][1], [0, 0, 255], 6)
        cv2.imshow('frame', frame)
        if wait_flag:
            cv2.waitKey(0)
        else:
            cv2.waitKey(1)


# Given a list of bounding boxes, return the average bounding box. 
Example #5
Source File: util.py    From SpaceXtract with MIT License 6 votes vote down vote up
def find_anchor(self, cap, start=0, end=1, maxiter=10):
        if not isinstance(self.extractor, RelativeExtract):
            return False

        original_location = cap.get(cv2.CAP_PROP_POS_FRAMES)

        for i in range(maxiter):
            pos = random.uniform(start, end)

            cap.set(cv2.CAP_PROP_POS_FRAMES,  pos*cap.get(cv2.CAP_PROP_FRAME_COUNT))
            _, frame = cap.read()

            if self.extractor.prepare_image_dict(frame):
                return True

        cap.set(cv2.CAP_PROP_POS_FRAMES, original_location)

        return False 
Example #6
Source File: util.py    From SpaceXtract with MIT License 6 votes vote down vote up
def skip_from_launch(self, cap, key, time, thresh=None):
        """
        Move the capture to T+time (time can be negative) and returns the frame index.
        :param cap: OpenCV capture
        :param time: delta time from launch to skip to
        :return: index of requested frame
        """        
        if thresh is None:
            thresh = self.extractor.image_dict[key][2]

        number_of_frames = int(cap.get(cv2.CAP_PROP_FPS) * time) + self.search_switch(cap, key, thresh)

        number_of_frames = max(number_of_frames, 0)
        number_of_frames = min(number_of_frames, cap.get(cv2.CAP_PROP_FRAME_COUNT))

        cap.set(cv2.CAP_PROP_POS_FRAMES, number_of_frames)

        return number_of_frames 
Example #7
Source File: util.py    From SpaceXtract with MIT License 6 votes vote down vote up
def search_switch(self, cap, key, thresh=0.5):
        left = 0
        right = cap.get(cv2.CAP_PROP_FRAME_COUNT) - 1

        cap.set(cv2.CAP_PROP_POS_FRAMES, int((right + left) / 2))

        while right > left + 1:
            _, frame = cap.read()

            image = self.extractor.prepare_frame(frame, self.extractor.image_dict[key][0])

            if not self.extractor.exists(image, self.extractor.image_dict[key][1][0], thresh):
                left = int((right + left) / 2)
            else:
                right = int((right + left) / 2)

            cap.set(cv2.CAP_PROP_POS_FRAMES, int((right + left) / 2))

        cap.set(cv2.CAP_PROP_POS_FRAMES, left)

        return left 
Example #8
Source File: clip_filter.py    From youtube-gesture-dataset with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_picture(self):
        sampling_interval = int(math.floor(self.scene_length / 5))
        sampling_frames = list(range(self.start_frame_no + sampling_interval,
                                     self.end_frame_no - sampling_interval + 1, sampling_interval))
        frames = []
        for frame_no in sampling_frames:
            self.video.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
            ret, frame = self.video.read()
            frames.append(frame)

        diff = 0
        n_diff = 0
        for frame, next_frame in zip(frames, frames[1:]):
            diff += cv2.norm(frame, next_frame, cv2.NORM_L1)  # abs diff
            n_diff += 1
        diff /= n_diff
        self.debugging_info[4] = round(diff, 0)

        return diff < 3000000 
Example #9
Source File: track_logger.py    From Multi-Camera-Object-Tracking with GNU General Public License v3.0 6 votes vote down vote up
def write_to_trackfile(track_info):
    # st = time.time()
    with open(WORK_DIR + "/METADATA/" + "trackfile.txt", "a+") as f:
        for item in track_info:
            f.write(str(item) + "\n")
            # print(str(item) + "\n")
        f.close()
    # et = time.time()
    # print ("write time:", et - st)
    # sys.exit()
    
#uncomment to use as stand-alone file
# start_frame = 8*3
# vid = VIDEO_PATH + "/cam_8.avi"
# cap = cv2.VideoCapture(vid)
# cap.set(cv2.CAP_PROP_FPS, 8)
# cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
# ok, frame = cap.read()
# bbox = selectROI(frame)
# track(0,cap,bbox,2)


# cam_id, cap, bbox, data_inc 
Example #10
Source File: video_io.py    From DetectAndTrack with Apache License 2.0 6 votes vote down vote up
def _get_frame_from_capture(cap, frame_number, filename, total_frames):
    frame_pos_const = cv2.cv.CV_CAP_PROP_POS_FRAMES if \
        cv2.__version__.startswith('2') else cv2.CAP_PROP_POS_FRAMES
    if (cap.get(frame_pos_const) != int(frame_number)):
        # Following is an expensive operation; avoid if possible
        cap.set(frame_pos_const, int(frame_number))
    success, I = cap.read()
    if not success:
        logger.error('Unable to read frame {} (out-of {}) from {}. Using 0s.'
                     .format(frame_number, total_frames, filename))
    elif I.max() > 256 or I.min() < 0:
        logger.error('Invalid values detected when reading frame {} '
                     'from {}. Using 0s.'.format(frame_number, filename))
    else:
        return I
    return cfg.PIXEL_MEANS 
Example #11
Source File: video_iterator.py    From PyTorch-MFNet with MIT License 6 votes vote down vote up
def count_frames(self, check_validity=False):
        offset = 0
        if self.vid_path.endswith('.flv'):
            offset = -1
        unverified_frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) + offset
        if check_validity:
            verified_frame_count = 0
            for i in range(unverified_frame_count):
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, i)
                if not self.cap.grab():
                    logging.warning("VideoIter:: >> frame (start from 0) {} corrupted in {}".format(i, self.vid_path))
                    break
                verified_frame_count = i + 1
            self.frame_count = verified_frame_count
        else:
            self.frame_count = unverified_frame_count
        assert self.frame_count > 0, "VideoIter:: Video: `{}' has no frames".format(self.vid_path)
        return self.frame_count 
Example #12
Source File: train_featurizer.py    From HardRLWithYoutube with MIT License 6 votes vote down vote up
def generate_dataset(videos_path, framerate, width, height):
    """Converts videos from specified path to ndarrays of shape [numberOfVideos, -1, width, height, 1]

    Args:
        videos_path: Inside the 'videos/' directory, the name of the subdirectory for videos.
        framerate: The desired framerate of the dataset.
        width: The width we will resize the videos to.
        height: The height we will resize the videos to.

    Returns:
        The dataset with the new size and framerate, and converted to monochromatic.

    """
    dataset = []
    video_index = 0
    for playlist in os.listdir('videos/' + videos_path):
        for video_name in os.listdir('videos/{}/{}'.format(videos_path, playlist)):
            dataset.append([])
            print('Video: {}'.format(video_name))
            video = cv2.VideoCapture('videos/{}/{}/{}'.format(videos_path, playlist, video_name))
            while video.isOpened():
                success, frame = video.read()
                if success:
                    frame = preprocess_image(frame, width, height)
                    dataset[video_index].append(frame)

                    frame_index = video.get(cv2.CAP_PROP_POS_FRAMES)
                    video_framerate = video.get(cv2.CAP_PROP_FPS)
                    video.set(cv2.CAP_PROP_POS_FRAMES, frame_index + video_framerate // framerate)
                    last_frame_index = video.get(cv2.CAP_PROP_FRAME_COUNT)
                    if frame_index >= last_frame_index:
                        # Video is over
                        break

                    
                else:
                    break
            dataset[video_index] = np.reshape(dataset[video_index], (-1, width, height, 1))
            video_index += 1
    return dataset 
Example #13
Source File: video.py    From cvcalib with Apache License 2.0 5 votes vote down vote up
def read_at_pos(self, ix_frame):
        self.cap.set(cv2.CAP_PROP_POS_FRAMES, ix_frame)
        self.more_frames_remain, self.frame = self.cap.read() 
Example #14
Source File: local_common.py    From DeepPicar-v2 with GNU General Public License v2.0 5 votes vote down vote up
def cv2_current_frame(cap):
    x = cap.get(cv2.CAP_PROP_POS_FRAMES)
    assert x.is_integer()
    return int(x) 
Example #15
Source File: local_common.py    From DeepPicar-v2 with GNU General Public License v2.0 5 votes vote down vote up
def cv2_goto_frame(cap, frame_id):
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_id)
    assert cv2_current_frame(cap) == frame_id 
Example #16
Source File: video_iterator.py    From PyTorch-MFNet with MIT License 5 votes vote down vote up
def extract_frames_fast(self, idxs, force_color=True):
        assert self.cap is not None, "No opened video."
        if len(idxs) < 1:
            return []

        frames = []
        pre_idx = max(idxs)
        for idx in idxs:
            assert (self.frame_count < 0) or (idx < self.frame_count), \
                "idxs: {} > total valid frames({})".format(idxs, self.frame_count)
            if pre_idx != (idx - 1):
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
            res, frame = self.cap.read() # in BGR/GRAY format
            pre_idx = idx
            if not res:
                self.faulty_frame = idx
                return None
            if len(frame.shape) < 3:
                if force_color:
                    # Convert Gray to RGB
                    frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
            else:
                # Convert BGR to RGB
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frames.append(frame)
        return frames 
Example #17
Source File: utilities.py    From minian with GNU General Public License v3.0 5 votes vote down vote up
def load_avi_perframe(fname, fid):
    cap = cv2.VideoCapture(fname)
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    cap.set(cv2.CAP_PROP_POS_FRAMES, fid)
    ret, fm = cap.read()
    if ret:
        return np.flip(
            cv2.cvtColor(fm, cv2.COLOR_RGB2GRAY), axis=0)
    else:
        print("frame read failed for frame {}".format(fid))
        return np.zeros((h, w)) 
Example #18
Source File: video_sources.py    From OpenCV-Video-Label with GNU General Public License v3.0 5 votes vote down vote up
def set(self, frame_num):
        self.stream.set(cv2.CAP_PROP_POS_FRAMES, frame_num)

    # returns the current frame number 
Example #19
Source File: demo_net.py    From SlowFast with Apache License 2.0 5 votes vote down vote up
def __next__(self):
        was_read, frame = self.cap.read()
        if not was_read:
            ## reiterate the video instead of quiting.
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
            frame = None

        return was_read, frame 
Example #20
Source File: tracklets.py    From DeepLabCut with GNU Lesser General Public License v3.0 5 votes vote down vote up
def on_change(self, val):
        self.curr_frame = int(val)
        self.video.set(cv2.CAP_PROP_POS_FRAMES, self.curr_frame)
        img = self._read_frame()
        if img is not None:
            # Automatically disable the draggable points
            if self.draggable:
                self.drag_toggle.set_active(False)

            self.im.set_array(img)
            self.display_points(self.curr_frame)
            self.display_trails(self.curr_frame)
            self.update_vlines(self.curr_frame) 
Example #21
Source File: data_utils.py    From youtube-gesture-dataset with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_current_frame(self, cur_frame_no):
        self.video.set(cv2.CAP_PROP_POS_FRAMES, cur_frame_no)


###############################################################################
# CLIP 
Example #22
Source File: Demo_OpenCV.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    # ---===--- Get the filename --- #
    filename = sg.PopupGetFile('Filename to play')
    if filename is None:
        exit(69)
    vidFile = cv.VideoCapture(filename)
    # ---===--- Get some Stats --- #
    num_frames = vidFile.get(cv.CAP_PROP_FRAME_COUNT)
    fps = vidFile.get(cv.CAP_PROP_FPS)

    sg.ChangeLookAndFeel('Black')

    # ---===--- define the window layout --- #
    layout = [[sg.Text('OpenCV Demo', size=(15, 1), font='Helvetica 20')],
              [sg.Image(filename='', key='_image_')],
              [sg.Slider(range=(0, num_frames), size=(60, 10), orientation='h', key='_slider_')],
              [sg.Button('Exit', size=(7, 1), pad=((600, 0), 3), font='Helvetica 14')]]

    # create the window and show it without the plot
    window = sg.Window('Demo Application - OpenCV Integration', no_titlebar=False, location=(0,0)).Layout(layout)

    image_elem = window.Element('_image_')    # locate the elements we'll be updating. Does the search only 1 time
    slider_elem = window.Element('_slider_')

    # ---===--- LOOP through video file by frame --- #
    cur_frame = 0
    while vidFile.isOpened():
        event, values = window.Read(timeout=0)
        if event in ('Exit', None):
            exit(69)
        ret, frame = vidFile.read()
        if not ret:  # if out of data stop looping
            break
        if int(values['_slider_']) != cur_frame-1:        # if someone moved the slider manually, the jump to that frame
            cur_frame = int(values['_slider_'])
            vidFile.set(cv.CAP_PROP_POS_FRAMES, cur_frame)
        slider_elem.Update(cur_frame)
        cur_frame += 1

        imgbytes = cv.imencode('.png', frame)[1].tobytes()  # ditto
        image_elem.Update(data=imgbytes) 
Example #23
Source File: video_viewer.py    From deepdiy with MIT License 5 votes vote down vote up
def fetch_frame(self,*args):
		'''Read a new frame, then render()'''
		prev_frame_idx = self.cap.get(cv2.CAP_PROP_POS_FRAMES)
		if self.frame_idx != prev_frame_idx +1:
			self.cap.set(cv2.CAP_PROP_POS_FRAMES,self.frame_idx)
		ret, frame = self.cap.read()
		if ret==True:
			self.frame = cv2.flip(frame,0)
			self.render()
		else:
			frame=None
			self.status = 'end' 
Example #24
Source File: image_stack_capture.py    From deepdiy with MIT License 5 votes vote down vote up
def set(self,param,value):
		if param == cv2.CAP_PROP_POS_FRAMES:
			self.pos_frames = int(value) 
Example #25
Source File: image_stack_capture.py    From deepdiy with MIT License 5 votes vote down vote up
def get(self,param):
		if param == cv2.CAP_PROP_FRAME_COUNT:
			return self.frame_count
		if param == cv2.CAP_PROP_POS_FRAMES:
			return self.pos_frames 
Example #26
Source File: media.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def load_video_frame(self, filename):
        """ Load a requested frame from video """
        frame = os.path.splitext(filename)[0]
        logger.trace("Loading video frame: '%s'", frame)
        frame_no = int(frame[frame.rfind("_") + 1:]) - 1
        self.vid_reader.set(cv2.CAP_PROP_POS_FRAMES, frame_no)  # pylint: disable=no-member
        _, image = self.vid_reader.read()
        # TODO imageio single frame seek seems slow. Look into this
        # self.vid_reader.set_image_index(frame_no)
        # image = self.vid_reader.get_next_data()[:, :, ::-1]
        return image 
Example #27
Source File: video_sources.py    From OpenCV-Video-Label with GNU General Public License v3.0 5 votes vote down vote up
def set(self, _):
        self.stream.set(cv2.CAP_PROP_POS_FRAMES, 0)

    # return 0, function to prevent errors 
Example #28
Source File: video_sources.py    From OpenCV-Video-Label with GNU General Public License v3.0 5 votes vote down vote up
def set(self, _):
        self.stream.set(cv2.CAP_PROP_POS_FRAMES, 0)

    # return 0, function to prevent errors 
Example #29
Source File: video_sources.py    From OpenCV-Video-Label with GNU General Public License v3.0 5 votes vote down vote up
def get(self, _):
        return self.stream.get(cv2.CAP_PROP_POS_FRAMES)

    # release the video 
Example #30
Source File: data_reader.py    From open_model_zoo with Apache License 2.0 5 votes vote down vote up
def reset(self):
        self.current = -1
        self.videocap.set(cv2.CAP_PROP_POS_FRAMES, 0)