How to use the imageio.get_reader function in imageio

To help you get started, we’ve selected a few imageio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github imageio / imageio / tests / test_tifffile.py View on Github external
im3 = imageio.imread(filename3)
    assert im1.ndim == 3
    assert im1.shape == im3.shape
    assert (im1 == im3).all()
    
    # Ensure imread + imwrite works round trip - volume like
    filename3 = os.path.join(test_dir, 'test_tiff2.tiff')
    im1 = imageio.volread(filename1)
    imageio.volwrite(filename3, im1)
    im3 = imageio.volread(filename3)
    assert im1.ndim == 4
    assert im1.shape == im3.shape
    assert (im1 == im3).all()

    # Read metadata
    md = imageio.get_reader(filename2).get_meta_data()
    assert md['is_imagej'] is None
    assert md['description'] == 'shape=(2,3,10,10)'
    assert md['description1'] == ''
    assert md['datetime'] == datetime.datetime(2015, 5, 9, 9, 8, 29)
    assert md['software'] == 'tifffile.py'

    # Write metadata
    dt = datetime.datetime(2018, 8, 6, 15, 35, 5)
    w = imageio.get_writer(filename1, software='testsoftware')
    w.append_data(np.zeros((10, 10)), meta={'description': 'test desc',
                                            'datetime': dt})
    w.close()
    r = imageio.get_reader(filename1)
    md = r.get_meta_data()
    assert 'datetime' in md
    assert md['datetime'] == dt
github MDSplus / mdsplus / pydevices / MitDevices / raspicam.py View on Github external
compressed=int(self.compressed)
        filename = "%s.%s"%(self.fileName(), ('h264' if compressed else 'rgb'), )
        if self.debugging:
            print "raspicam: reading %s"%filename
        self.times.record = MDSplus.Data.compile('$1 : $1+($2-1)/float($3) : 1./$3', self.trigger, self.num_frames, self.fps)
        self.intensity.record = MDSplus.Data.compile("MAKE_SIGNAL($*$+$*$+$*$,*,$)",self.r_frames, self.r_coeff, self.g_frames, self.g_coeff, self.b_frames, self.b_coeff, self.times)
        if not compressed:
            img = np.fromfile(filename, dtype=np.uint8)
            img=img.reshape(num_frames, height, width, 3)
            self.r_frames.record = img[:,:,:,0]
            self.g_frames.record = img[:,:,:,1]
            self.b_frames.record = img[:,:,:,2]
        else:
            ans = None
            count = 0
            vid = imageio.get_reader(filename, 'ffmpeg')
            meta = vid.get_meta_data()
            ans = np.empty((num_frames, height, width, 3),dtype=np.uint8)
            try:
                for i in range(num_frames):
                    im = vid.get_data(i)
                    ans[i,:,:,:] = im
            except Exception, e:
                print e
            if self.debugging:
                print "chop the answer to the number of frames"
            ans = ans[0:i-1,:,:,:]
            if self.debugging:
                print "shape is ", ans.shape
                print ans[:,:,:,0][0]
            self.r_frames.record=ans[:,:,:,0]
            if self.debugging:
github vijayvee / video-captioning / utils.py View on Github external
def playVideo(video_urls):
    video = imageio.get_reader(YOUTUBE_CLIPS_DIR + video_urls[0] + '.avi','ffmpeg')
    for frame in video:
        fr = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
        cv2.imshow('frame',fr)
        if cv2.waitKey(40) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()
github jianzfb / antgo / antgo / dataflow / dataset / simplevideos.py View on Github external
def _video_iterator(self, video_path):
    reader = imageio.get_reader(video_path)
    for im in reader:
      img_data = np.fromstring(im.tobytes(), dtype=np.uint8)
      img_data = img_data.reshape((im.shape[0], im.shape[1], im.shape[2]))
      yield img_data, None
github pambot / ozymandias / src / video_preprocess.py View on Github external
def main():
    """Preprocess all video files in `raw/` but ignore malformed videos"""
    video_files = glob.glob('raw/*.mp4')
    
    for vf in video_files:
        reader = imageio.get_reader(vf, format='ffmpeg')
        writer = imageio.get_writer(vf.replace('raw/', 'data/'), format='ffmpeg')
        try:
            format_frames(reader, writer)
        except RuntimeError:
            continue
github microsoft / CNTK / Examples / Video / GettingStarted / Python / Conv3D_UCF11.py View on Github external
def _select_features(self, video_file):
        '''
        Select a sequence of frames from video_file and return them as
        a Tensor.
        '''
        video_reader = imageio.get_reader(video_file, 'ffmpeg')
        num_frames   = len(video_reader)
        if self.sequence_length > num_frames:
            raise ValueError('Sequence length {} is larger then the total number of frames {} in {}.'.format(self.sequence_length, num_frames, video_file))

        # select which sequence frames to use.
        step = 1
        expanded_sequence = self.sequence_length
        if num_frames > 2*self.sequence_length:
            step = 2
            expanded_sequence = 2*self.sequence_length

        seq_start = int(num_frames/2) - int(expanded_sequence/2)
        if self.is_training:
            seq_start = randint(0, num_frames - expanded_sequence)

        frame_range = [seq_start + step*i for i in range(self.sequence_length)]
github pambot / ozymandias / src / ozy_producer.py View on Github external
def main(n):
    """Stream the video into a Kafka producer in an infinite loop"""
    
    topic = choose_channel(n)
    video_reader = imageio.get_reader(DATA + topic + '.mp4', 'ffmpeg')
    metadata = video_reader.get_meta_data()
    fps = metadata['fps']

    producer = KafkaProducer(bootstrap_servers='localhost:9092',
                             batch_size=15728640,
                             linger_ms=1000,
                             max_request_size=15728640,
                             value_serializer=lambda v: json.dumps(v.tolist()))
    
    while True:
        video_loop(video_reader, producer, topic, fps)
github NeuromorphicProcessorProject / snn_toolbox / snntoolbox / datasets / aedat / avi_to_lmdb.py View on Github external
def avi_to_frame_list(avi_filename, gray):
    """Creates a list of frames starting from an AVI movie.
    Inverts axes to have num_channels, height, width in this order.

    Parameters
    ----------

    avi_filename: name of the AVI movie
    gray: if True, the resulting images are treated as grey images with only
          one channel. If False, the images have three channels.
    """
    print('Loading {}'.format(avi_filename))
    vid = imageio.get_reader(avi_filename, 'ffmpeg')
    if gray:
        data = [np.mean(np.moveaxis(im, 2, 0), axis=0, keepdims=True)
                for im in vid.iter_data()]
        print('Loaded grayscale images.')

    else:
        data = [np.moveaxis(im, 2, 0) for im in vid.iter_data()]
        print('Loaded RGB images.')
    return data
github jayshah19949596 / DeepSign-A-Deep-Learning-Architecture-for-Sign-Language-Recognition / utils / utility.py View on Github external
This function prepares batches by reading the video and extracting
    frames which is used as one mini-batch in training

    :param video_path: string
                       path to video which is to be read

    :param frame_limit: int
                        limiting the number frames which is to be returned
                        if the number of frames in the video is > frame_limit
                        then random sampling will be carried out to extract frames exactly of frame_limit
    :param resize: tuple of shape 2 elements
                   resizing the frames
    :return: frame_batch : numpy array of shape (batch_size, height, width, 1)
    """
    sampling = False
    video = imageio.get_reader(video_path, 'ffmpeg')
    frame_batch = np.zeros(resize)
    frame_batch = frame_batch.reshape((1, resize[0], resize[1]))
    if frame_limit < len(video):
        sampling = True
        sampling_list = random.sample(range(0, len(video)-1), frame_limit)

    for i in range(len(video)):
        if sampling and i not in sampling_list:
            continue
        frame = video.get_data(i)
        red_channel = frame[:, :, 0]
        red_channel = cv_utils.resize(red_channel, resize)
        red_channel[red_channel > 0] == 255.0
        red_channel = red_channel / 255.0
        cv2.imshow("bg_subtraction", red_channel)
        if cv2.waitKey(25) & 0xFF == ord('q'):