本文整理汇总了Python中imageio.get_reader方法的典型用法代码示例。如果您正苦于以下问题:Python imageio.get_reader方法的具体用法?Python imageio.get_reader怎么用?Python imageio.get_reader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类imageio
的用法示例。
在下文中一共展示了imageio.get_reader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: avi_to_frame_list
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
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
示例2: main
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def main():
reader = imageio.get_reader("person_0_tube.mp4")
frames = []
for cur_frame in reader:
frames.append(cur_frame)
input_tube = np.stack(frames[:32], axis=0)
input_tube = np.expand_dims(input_tube, axis=0) # batch dimension
detector_dict = set_up_detector()
prediction_probabilites = detect_on_tube(input_tube, detector_dict)
top_k = 5
top_classes = np.argsort(prediction_probabilites[0,:])[:-top_k-1:-1]
print("Results")
for ii in range(top_k):
class_id = top_classes[ii]
class_str = act.ACTION_STRINGS[class_id]
class_prob = prediction_probabilites[0,class_id]
print("%.10s : %.3f" % (class_str, class_prob))
cv2.imshow('midframe', input_tube[0,16,:,:,::-1])
cv2.waitKey(0)
示例3: test_screenrecord
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def test_screenrecord(d: u2.Device):
with pytest.raises(RuntimeError):
d.screenrecord.stop()
d.screenrecord("output.mp4", fps=10)
start = time.time()
with pytest.raises(RuntimeError):
d.screenrecord("output2.mp4")
time.sleep(3.0)
d.screenrecord.stop()
print("Time used:", time.time() - start)
# check
with imageio.get_reader("output.mp4") as f:
meta = f.get_meta_data()
assert isinstance(meta, dict)
from pprint import pprint
pprint(meta)
示例4: main
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
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)
示例5: _get_fps
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def _get_fps(self):
""" Get the Frames per Second.
If the input is a folder of images than 25.0 will be returned, as it is not possible to
calculate the fps just from frames alone. For video files the correct FPS will be returned.
Returns
-------
float: The Frames per Second of the input sources
"""
if self._is_video:
reader = imageio.get_reader(self.location, "ffmpeg")
retval = reader.get_meta_data()["fps"]
reader.close()
else:
retval = 25.0
logger.debug(retval)
return retval
示例6: _from_video
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def _from_video(self):
""" Generator for loading frames from a video
Yields
------
filename: str
The dummy filename of the loaded video frame.
image: numpy.ndarray
The loaded video frame.
"""
logger.debug("Loading frames from video: '%s'", self.location)
reader = imageio.get_reader(self.location, "ffmpeg")
for idx, frame in enumerate(reader):
if idx in self._skip_list:
logger.trace("Skipping frame %s due to skip list", idx)
continue
# Convert to BGR for cv2 compatibility
frame = frame[:, :, ::-1]
filename = self._dummy_video_framename(idx)
logger.trace("Loading video frame: '%s'", filename)
yield filename, frame
reader.close()
示例7: _load_one_video_frame
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def _load_one_video_frame(self, frame_no):
""" Obtain a single frame from a video file.
Parameters
----------
frame_no: int
The frame index for the required frame
Returns
------
:class:`numpy.ndarray`
The image for the requested frame index,
"""
logger.trace("Loading video frame: %s", frame_no)
reader = imageio.get_reader(self._args.input_dir, "ffmpeg")
reader.set_image_index(frame_no - 1)
frame = reader.get_next_data()[:, :, ::-1]
reader.close()
return frame
示例8: __init__
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def __init__(self, fname, format=None, resize=None, anti_aliasing=False,
electrodes=None, metadata=None, compress=False,
interp_method='linear', extrapolate=False):
# Open the video reader:
reader = video_reader(fname, format=format)
# Combine video metadata with user-specified metadata:
meta = reader.get_meta_data()
if metadata is not None:
meta.update(metadata)
meta['source'] = fname
# Read the video:
vid = [frame for frame in reader]
# Consider downscaling before doing anything else (with anti-aliasing,
# this can take a while):
if resize is not None:
vid = parfor(img_resize, vid, func_args=[resize],
func_kwargs={'anti_aliasing': anti_aliasing})
if vid[0].ndim == 3 and vid[0].shape[-1] == 3:
vid = parfor(rgb2gray, vid)
vid = np.array(parfor(img_as_float, vid)).transpose((1, 2, 0))
# Infer the time points from the video frame rate:
n_frames = vid.shape[-1]
time = np.arange(n_frames) * meta['fps']
# Call the Stimulus constructor:
super(VideoStimulus, self).__init__(vid.reshape((-1, n_frames)),
time=time, electrodes=electrodes,
metadata=meta, compress=compress,
interp_method=interp_method,
extrapolate=extrapolate)
示例9: __init__
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def __init__(self, path):
self.path = path
self.container = imageio.get_reader(path, 'ffmpeg')
self.length = self.container.count_frames()
self.fps = self.container.get_meta_data()['fps']
示例10: __init__
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def __init__(self, vid_path, start=0, seq_len=1, fps=29.97):
""" The VideoReader serves a generator of frame-sequences as needed. To increase performance, sequential
frame access is enforced, and frames are cached into a buffer to allow for quicker repeated and
sequential accesses within the allocated buffer.
TODO: Buffer implementation. Could be implemented by taking a cache_size param for max(caption_size) and
keeping track lo/hi indices for when to update. See `_updateCache` for draft.
Note memory usage may grow significantly with high-resolution video or large cache sizes, calculated by the
following formula:
```
bytes = seq_len * height * width * channels
```
A 1080p (1920x1080) video with sequence length of 30, or approximately 1 second of 30fps footage equates to:
```
30 * 1080 * 1920 * 3 bytes ~ 186MB
```
:param vid_path: Path of the video to read from.
:param start: The starting frame index to begin reading from.
:param seq_len: The length of the sequence of frames to serve.
"""
assert os.path.isfile(vid_path)
reader = imageio.get_reader(vid_path)
vid_len = reader.get_length()
# State.
self.lo = start
self._reader = reader
self.cache = collections.deque(maxlen=seq_len)
self.buf = np.empty(shape=(seq_len,), dtype=np.ndarray)
# For convenience.
self._seq_len = seq_len
self._vid_len = vid_len
self._fps = fps
示例11: test_local_video
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def test_local_video():
main_folder_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
obj_detection_graph = os.path.join(main_folder_path, 'object_detection/weights/batched_zoo/faster_rcnn_nas_coco_2018_01_28/batched_graph/frozen_inference_graph.pb')
print("Loading object detection model at %s" % obj_detection_graph)
Obj_Detector = obj.Object_Detector(obj_detection_graph)
test_vid_path = "chase1Person1View3Point0.mp4"
print('Testing on %s' % test_vid_path)
reader = imageio.get_reader(test_vid_path, 'ffmpeg')
fps = reader.get_meta_data()['fps'] // 2
out_vid_path = "chase1Person1View3Point0_out.mp4"
writer = imageio.get_writer(out_vid_path, fps=fps)
print("Writing output video on %s" %out_vid_path)
frame_cnt = 0
for test_img in reader:
frame_cnt += 1
if frame_cnt % 2 == 0:
continue
print("frame_cnt: %i" %frame_cnt)
expanded_img = np.expand_dims(test_img, axis=0)
detection_list = Obj_Detector.detect_objects_in_np(expanded_img)
out_img = visualize_results(test_img, detection_list, display=False)
writer.append_data(out_img)
writer.close()
示例12: test_tracking_local_video
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def test_tracking_local_video():
main_folder_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# obj_detection_graph = os.path.join(main_folder_path, 'object_detection/weights/batched_zoo/faster_rcnn_nas_coco_2018_01_28/batched_graph/frozen_inference_graph.pb')
obj_detection_graph = os.path.join(main_folder_path, 'object_detection/weights/batched_zoo/faster_rcnn_nas_lowproposals_coco_2018_01_28/batched_graph/frozen_inference_graph.pb')
print("Loading object detection model at %s" % obj_detection_graph)
Obj_Detector = obj.Object_Detector(obj_detection_graph)
Tracker = obj.Tracker()
#test_vid_path = "chase1Person1View3Point0.mp4"
#test_vid_path = "VIRAT_S_000003_9_00.mp4"
test_vid_path = "VIRAT_S_000101_1_00.mp4"
print('Testing on %s' % test_vid_path)
reader = imageio.get_reader(test_vid_path, 'ffmpeg')
fps = reader.get_meta_data()['fps'] // 2
#out_vid_path = "chase1Person1View3Point0_out.mp4"
#out_vid_path = "VIRAT_S_000003_9_00_out.mp4"
out_vid_path = "VIRAT_S_000101_1_00_out.mp4"
writer = imageio.get_writer(out_vid_path, fps=fps)
print("Writing output video on %s" %out_vid_path)
frame_cnt = 0
for test_img in reader:
frame_cnt += 1
if frame_cnt % 2 == 0:
continue
print("frame_cnt: %i" %frame_cnt)
expanded_img = np.expand_dims(test_img, axis=0)
detection_list = Obj_Detector.detect_objects_in_np(expanded_img)
detection_info = [info[0] for info in detection_list]
Tracker.update_tracker(detection_info, test_img)
#print(Tracker.active_actors)
out_img = visualize_results_from_tracking(test_img, Tracker.active_actors, Tracker.inactive_actors, display=False)
writer.append_data(out_img)
writer.close()
示例13: make_gif
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def make_gif(image, iteration_number, save_path, model_name, max_frames_per_gif=100):
# Make gif
gif_frames = []
# Read old gif frames
try:
gif_frames_reader = imageio.get_reader(os.path.join(save_path, model_name + ".gif"))
for frame in gif_frames_reader:
gif_frames.append(frame[:, :, :3])
except:
pass
# Append new frame
im = cv2.putText(np.concatenate((np.zeros((32, image.shape[1], image.shape[2])), image), axis=0),
'iter %s' % str(iteration_number), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.LINE_AA).astype('uint8')
gif_frames.append(im)
# If frames exceeds, save as different file
if len(gif_frames) > max_frames_per_gif:
print("Splitting the GIF...")
gif_frames_00 = gif_frames[:max_frames_per_gif]
num_of_gifs_already_saved = len(glob.glob(os.path.join(save_path, model_name + "_*.gif")))
print("Saving", os.path.join(save_path, model_name + "_%05d.gif" % (num_of_gifs_already_saved)))
imageio.mimsave(os.path.join(save_path, model_name + "_%05d.gif" % (num_of_gifs_already_saved)), gif_frames_00)
gif_frames = gif_frames[max_frames_per_gif:]
# Save gif
# print("Saving", os.path.join(save_path, model_name + ".gif"))
imageio.mimsave(os.path.join(save_path, model_name + ".gif"), gif_frames)
示例14: extract_frames
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def extract_frames(video_path):
def convert_frame(arg):
return Image.fromarray(arg[:, :, :3], mode='RGB')
video_reader = imageio.get_reader(video_path)
fps = video_reader.get_meta_data().get('fps', None)
frames = [convert_frame(x) for x in video_reader]
return frames, fps
示例15: _get_data
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import get_reader [as 别名]
def _get_data(file: Path, index: int) -> np.ndarray:
with imageio.get_reader(file) as reader:
return np.asarray(reader.get_data(index))