def test_invalidfile(): filename = test_dir+'/empty.mp4' with open(filename, 'w'): pass with raises(IOError): imageio.read(filename)
def test_webcam(): need_internet() try: imageio.read("<video0>") except Exception: skip("no web cam")
def test_write_not_contiguous(): R = imageio.read(get_remote_file("images/cockatoo.mp4"), "ffmpeg") assert R.format is imageio.formats["ffmpeg"] fname1 = get_remote_file("images/cockatoo.mp4", test_dir) fname2 = fname1[:-4] + ".out.mp4" # Read ims1 = [] with imageio.read(fname1, "ffmpeg") as R: for i in range(10): im = R.get_next_data() ims1.append(im) # Save non contiguous data with imageio.save(fname2, "ffmpeg") as W: for im in ims1: # DOn't slice the first dimension since it won't be # a multiple of 16. This will cause the writer to expand # the data to make it fit, we won't be able to compare # the difference between the saved and the original images. im = im[:, ::2] assert not im.flags.c_contiguous W.append_data(im) ims2 = imageio.mimread(fname2, "ffmpeg") # Check for im1, im2 in zip(ims1, ims2): diff = np.abs(im1[:, ::2].astype(np.float32) - im2.astype(np.float32)) if IS_PYPY: assert (diff.sum() / diff.size) < 100 else: assert diff.mean() < 2.5
def test_read(): need_internet() R = imageio.read(get_remote_file("images/cockatoo.mp4"), "avbin") assert R.format is imageio.formats["avbin"] fname = get_remote_file("images/cockatoo.mp4", force_download="2014-11-05") reader = imageio.read(fname, "avbin") assert reader.get_length() == 280 assert "fps" in reader.get_meta_data() raises(Exception, imageio.save, "~/foo.mp4", "abin") # assert not reader.format.can_write(core.Request('test.mp4', 'wI')) for i in range(10): im = reader.get_next_data() assert im.shape == (720, 1280, 3) # todo: fix this # assert mean(im) > 100 and mean(im) < 115 KNOWN FAIL # We can rewind reader.get_data(0) # But not seek with raises(IndexError): reader.get_data(4)
def test_webcam(): need_internet() try: imageio.read('<video0>') except Exception: skip('no web cam')
def test_reader_more(): fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname3 = fname1[:-4] + '.stub.mp4' # Get meta data R = imageio.read(fname1, 'ffmpeg', loop=True) meta = R.get_meta_data() assert isinstance(meta, dict) assert 'fps' in meta R.close() # Test size argument im = imageio.read(fname1, 'ffmpeg', size=(50, 50)).get_data(0) assert im.shape == (50, 50, 3) im = imageio.read(fname1, 'ffmpeg', size='40x40').get_data(0) assert im.shape == (40, 40, 3) raises(ValueError, imageio.read, fname1, 'ffmpeg', size=20) raises(ValueError, imageio.read, fname1, 'ffmpeg', pixelformat=20) # Read invalid open(fname3, 'wb') raises(RuntimeError, imageio.read, fname3, 'ffmpeg') # Read printing info imageio.read(fname1, 'ffmpeg', print_info=True)
def test_animated_gif(): # Get images im = get_ref_im(4, 0, 0) ims = [] for i in range(10): im = im.copy() im[:, -5:, 0] = i * 20 ims.append(im) # Store - animated GIF always poops out RGB for float in (False, True): for colors in (3, 4): ims1 = ims[:] if float: ims1 = [x.astype(np.float32) / 256 for x in ims1] ims1 = [x[:, :, :colors] for x in ims1] fname = fnamebase + '.animated.%i.gif' % colors imageio.mimsave(fname, ims1, duration=0.2) # Retrieve ims2 = imageio.mimread(fname) ims1 = [x[:, :, :3] for x in ims] # fresh ref ims2 = [x[:, :, :3] for x in ims2] # discart alpha for im1, im2 in zip(ims1, ims2): assert_close(im1, im2, 1.1) # We can also store grayscale fname = fnamebase + '.animated.%i.gif' % 1 imageio.mimsave(fname, [x[:, :, 0] for x in ims], duration=0.2) imageio.mimsave(fname, [x[:, :, :1] for x in ims], duration=0.2) # Irragular duration. You probably want to check this manually (I did) duration = [0.1 for i in ims] for i in [2, 5, 7]: duration[i] = 0.5 imageio.mimsave(fnamebase + '.animated_irr.gif', ims, duration=duration) # Other parameters imageio.mimsave(fnamebase + '.animated.loop2.gif', ims, loop=2) R = imageio.read(fnamebase + '.animated.loop2.gif') W = imageio.save(fnamebase + '.animated.palettes100.gif', palettesize=100) assert W._palettesize == 128 # Fail raises(IndexError, R.get_meta_data, -1) raises(ValueError, imageio.mimsave, fname, ims, palettesize=300) raises(ValueError, imageio.mimsave, fname, ims, quantizer='foo') raises(ValueError, imageio.mimsave, fname, ims, duration='foo') # Test subrectangles imageio.mimsave(fnamebase + '.subno.gif', ims, subrectangles=False) imageio.mimsave(fnamebase + '.subyes.gif', ims, subrectangles=True) s1 = os.stat(fnamebase + '.subno.gif').st_size s2 = os.stat(fnamebase + '.subyes.gif').st_size assert s2 < s1 # Meta (dummy, because always {} assert isinstance(imageio.read(fname).get_meta_data(), dict)
def test_reader_more(): need_internet() fname1 = get_remote_file("images/cockatoo.mp4") fname3 = fname1[:-4] + ".stub.mp4" # Get meta data R = imageio.read(fname1, "avbin", loop=True) meta = R.get_meta_data() assert isinstance(meta, dict) assert "fps" in meta R.close() # Read all frames and test length R = imageio.read(get_remote_file("images/realshort.mp4"), "avbin") count = 0 while True: try: R.get_next_data() except IndexError: break else: count += 1 assert count == len(R) assert count in (35, 36) # allow one frame off size that we know # Test index error -1 raises(IndexError, R.get_data, -1) # Test loop R = imageio.read(get_remote_file("images/realshort.mp4"), "avbin", loop=1) im1 = R.get_next_data() for i in range(1, len(R)): R.get_next_data() im2 = R.get_next_data() im3 = R.get_data(0) assert (im1 == im2).all() assert (im1 == im3).all() R.close() # Test size when skipping empty frames, are there *any* valid frames? # todo: use mimread once 1) len(R) == inf, or 2) len(R) is correct R = imageio.read(get_remote_file("images/realshort.mp4"), "avbin", skipempty=True) ims = [] with R: try: while True: ims.append(R.get_next_data()) except IndexError: pass assert len(ims) > 20 # todo: should be 35/36 but with skipempty ... # Read invalid open(fname3, "wb") raises(IOError, imageio.read, fname3, "avbin")
def test_reader_more(): need_internet() fname1 = get_remote_file('images/cockatoo.mp4') fname3 = fname1[:-4] + '.stub.mp4' # Get meta data R = imageio.read(fname1, 'avbin', loop=True) meta = R.get_meta_data() assert isinstance(meta, dict) assert 'fps' in meta R.close() # Read all frames and test length R = imageio.read(get_remote_file('images/realshort.mp4'), 'avbin') count = 0 while True: try: R.get_next_data() except IndexError: break else: count += 1 assert count == len(R) assert count in (35, 36) # allow one frame off size that we know # Test index error -1 raises(IndexError, R.get_data, -1) # Test loop R = imageio.read(get_remote_file('images/realshort.mp4'), 'avbin', loop=1) im1 = R.get_next_data() for i in range(1, len(R)): R.get_next_data() im2 = R.get_next_data() im3 = R.get_data(0) assert (im1 == im2).all() assert (im1 == im3).all() R.close() # Test size when skipping empty frames, are there *any* valid frames? # todo: use mimread once 1) len(R) == inf, or 2) len(R) is correct R = imageio.read(get_remote_file('images/realshort.mp4'), 'avbin', skipempty=True) ims = [] with R: try: while True: ims.append(R.get_next_data()) except IndexError: pass assert len(ims) > 20 # todo: should be 35/36 but with skipempty ... # Read invalid open(fname3, 'wb') raises(IOError, imageio.read, fname3, 'avbin')
def test_invalidfile(): filename = test_dir+'/empty.mp4' with open(filename, 'w'): pass with raises(IOError): imageio.read(filename, 'avbin') # Check AVbinResult imageio.plugins.avbin.AVbinResult(imageio.plugins.avbin.AVBIN_RESULT_OK) for i in (2, 3, 4): with raises(RuntimeError): imageio.plugins.avbin.AVbinResult(i)
def test_invalidfile(): filename = test_dir + '/empty.mp4' with open(filename, 'w'): pass with raises(IOError): imageio.read(filename, 'avbin') # Check AVbinResult imageio.plugins.avbin.AVbinResult(imageio.plugins.avbin.AVBIN_RESULT_OK) for i in (2, 3, 4): with raises(RuntimeError): imageio.plugins.avbin.AVbinResult(i)
def test_read_and_write(): need_internet() R = imageio.read(get_remote_file('images/cockatoo.mp4'), 'ffmpeg') assert R.format is imageio.formats['ffmpeg'] fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname2 = fname1[:-4] + '.out.mp4' # Read ims1 = [] with imageio.read(fname1, 'ffmpeg') as R: for i in range(10): im = R.get_next_data() ims1.append(im) assert im.shape == (720, 1280, 3) assert (im.sum() / im.size) > 0 # pypy mean is broken assert im.sum() > 0 # Get arbitrary data im1 = R.get_data(120) assert im1.shape == (720, 1280, 3) # Set image index R.set_image_index(42) im2 = R.get_next_data() assert im2.shape == (720, 1280, 3) R.set_image_index(120) im3 = R.get_next_data() assert im3.shape == (720, 1280, 3) assert (im1 == im3).all() assert not (im1 == im2).all() # Save with imageio.save(fname2, 'ffmpeg') as W: for im in ims1: W.append_data(im) # Read the result ims2 = imageio.mimread(fname2, 'ffmpeg') assert len(ims1) == len(ims2) # Check for im1, im2 in zip(ims1, ims2): diff = np.abs(im1.astype(np.float32) - im2.astype(np.float32)) if IS_PYPY: assert (diff.sum() / diff.size) < 100 else: assert diff.mean() < 2.5
def extract_videos_and_run_rcnn(rootpath, rootpath_depth, frame_size): print(rootpath) rcnn = util.RCNN(plot_mode=True) for file in os.listdir(rootpath): # if 'view1' not in file: # continue if not file.endswith('.mp4'): continue filepath = join(rootpath, file) filepath_depth = join(rootpath_depth, file) folderpath = join(rootpath, file.split('.mp4')[0]) folderpath_depth = join(rootpath_depth, file.split('.mp4')[0]) print("save in", folderpath) debugpath = join(rootpath, 'debug', file.split('.mp4')[0]) if not os.path.exists(folderpath): os.makedirs(folderpath) if not os.path.exists(debugpath): os.makedirs(debugpath) if not os.path.exists(folderpath_depth): os.makedirs(folderpath_depth) imageio_video = imageio.read(filepath) imageio_video_depth = imageio.read(filepath_depth) snap_length = len(imageio_video) frames = np.zeros((snap_length, 3, *frame_size)) frames_depth = np.zeros((snap_length, 3, *frame_size)) i = 0 for frame, frame_depth in zip(imageio_video, imageio_video_depth): print("Process frame ", i) r, fig = rcnn.get_raw_rcnn_results(frame) save_name = '{0:05d}'.format(i) with open(join(folderpath, save_name + '.pkl'), 'wb') as handle: pickle.dump(r, handle, protocol=pickle.HIGHEST_PROTOCOL) plt.imsave(join(folderpath, save_name + '.jpg'), frame) plt.imsave(join(folderpath_depth, save_name + '.jpg'), frame_depth) if fig is not None: canvas = FigureCanvas(fig) ax = fig.gca() canvas.draw() # draw the canvas, cache the renderer output_img = np.array(fig.canvas.renderer._renderer) plt.imsave(join(debugpath, save_name + '.jpg'), output_img) plt.close(fig) i += 1 print("=" * 20)
def test_invalidfile(): need_internet() filename = test_dir + "/empty.mp4" with open(filename, "w"): pass with raises(IOError): imageio.read(filename, "avbin") # Check AVbinResult imageio.plugins.avbin.AVbinResult(imageio.plugins.avbin.AVBIN_RESULT_OK) for i in (2, 3, 4): with raises(RuntimeError): imageio.plugins.avbin.AVbinResult(i)
def final_stage_gif(): print("Finally, collating it all into one big gif...") with imageio.get_writer("output.gif", mode="I") as writer: for img in os.listdir("imgs"): image = imageio.read("imgs/" + img) writer.append_data(image) print("Done!")
def test_ico(): for float in (False, True): for crop in (0, 1, 2): for colors in (0, 1, 3, 4): fname = fnamebase + '%i.%i.%i.ico' % (float, crop, colors) rim = get_ref_im(colors, crop, float) imageio.imsave(fname, rim) im = imageio.imread(fname) mul = 255 if float else 1 assert_close(rim * mul, im, 0.1) # lossless # Meta data R = imageio.read(fnamebase + '0.0.0.ico') assert isinstance(R.get_meta_data(0), dict) assert isinstance(R.get_meta_data(None), dict) # But this print warning writer = imageio.save(fnamebase + 'I.ico') writer.set_meta_data({}) writer.close() # Parameters. Note that with makealpha, RGBA images are read in incorrectly im = imageio.imread(fnamebase + '0.0.0.ico', makealpha=True) assert im.ndim == 3 and im.shape[-1] == 4 # Parameter fail raises(TypeError, imageio.imread, fname, notavalidkwarg=True) raises(TypeError, imageio.imsave, fnamebase + '1.gif', im, notavalidk=True) # Multiple images im = get_ref_im(4, 0, 0) ims1 = im, np.column_stack([im, im]), np.row_stack([im, im]) imageio.mimsave(fnamebase + 'I.ico', ims1) ims2 = imageio.mimread(fnamebase + 'I.ico') for im1, im2 in zip(ims1, ims2): assert_close(im1, im2, 0.1)
def test_fits_reading(test_images): """Test reading fits""" simple = test_images / "simple.fits" multi = test_images / "multi.fits" compressed = test_images / "compressed.fits.fz" # One image im = imageio.imread(simple, format="fits") ims = imageio.mimread(simple, format="fits") assert (im == ims[0]).all() assert len(ims) == 1 # Multiple images ims = imageio.mimread(multi, format="fits") assert len(ims) == 3 R = imageio.read(multi, format="fits") assert R.format.name == "FITS" ims = list(R) # == [im for im in R] assert len(ims) == 3 # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data, None) # no meta data support raises(RuntimeError, R.get_meta_data, 0) # no meta data support # Compressed image im = imageio.imread(compressed, format="fits") assert im.shape == (2042, 3054)
def __init__(self, mode="rectangles", n_elements_max=5, L=1.0): super().__init__() self._image = imageio.read("./data/cage_meme.jpg").get_data(0) self._image = self._image / np.max(self._image) n_elements = np.random.randint(1, n_elements_max) self._mode = mode widths = np.random.random(size=(n_elements)) * 0.3 + 0.05 heights = np.random.random(size=(n_elements)) * 0.3 + 0.05 self._amps = 0.5 * (np.random.random(size=(n_elements)) - 0.5) + 1 self._shapes = [(width, height) for (width, height) in zip(widths, heights)] xs = np.random.random(size=(n_elements)) * (1 - 0.36) ys = np.random.random(size=(n_elements)) * (1 - 0.36) self._origins = [(x, y) for (x, y) in zip(xs, ys)] stdxs = np.random.random(size=(n_elements)) * 0.1 + 0.05 stdys = np.random.random(size=(n_elements)) * 0.1 + 0.05 self._stds = [(stdx, stdy) for (stdx, stdy) in zip(stdxs, stdys)] xs = np.random.random(size=(n_elements)) ys = np.random.random(size=(n_elements)) self._mus = [(x, y) for (x, y) in zip(xs, ys)]
def test_read_and_write(): fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname2 = fname1[:-4] + '.out.mp4' # Read ims1 = [] with imageio.read(fname1, 'ffmpeg') as R: for i in range(10): im = R.get_next_data() ims1.append(im) assert im.shape == (720, 1280, 3) assert (im.sum() / im.size) > 0 # pypy mean is broken assert im.sum() > 0 # Seek im = R.get_data(120) assert im.shape == (720, 1280, 3) # Save with imageio.save(fname2, 'ffmpeg') as W: for im in ims1: W.append_data(im) # Read the result ims2 = imageio.mimread(fname2, 'ffmpeg') assert len(ims1) == len(ims2) # Check for im1, im2 in zip(ims1, ims2): diff = np.abs(im1.astype(np.float32) - im2.astype(np.float32)) if IS_PYPY: assert (diff.sum() / diff.size) < 100 else: assert diff.mean() < 2.0
def test_simpleitk_reading_writing(): """ Test reading and saveing tiff """ im2 = np.ones((10, 10, 3), np.uint8) * 2 filename1 = os.path.join(test_dir, "test_tiff.tiff") # One image imageio.imsave(filename1, im2, "itk") im = imageio.imread(filename1, "itk") print(im.shape) ims = imageio.mimread(filename1, "itk") print(im2.shape) assert (im == im2).all() assert len(ims) == 1 # Mixed W = imageio.save(filename1, "itk") raises(RuntimeError, W.set_meta_data, 1) assert W.format.name == "ITK" W.append_data(im2) W.append_data(im2) W.close() # R = imageio.read(filename1, "itk") assert R.format.name == "ITK" ims = list(R) # == [im for im in R] assert (ims[0] == im2).all() # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data)
def test_fits_reading(): """ Test reading fits """ need_internet() # We keep the fits files in the imageio-binary repo if IS_PYPY: return # no support for fits format :( simple = get_remote_file('images/simple.fits') multi = get_remote_file('images/multi.fits') # One image im = imageio.imread(simple) ims = imageio.mimread(simple) assert (im == ims[0]).all() assert len(ims) == 1 # Multiple images ims = imageio.mimread(multi) assert len(ims) == 3 R = imageio.read(multi) assert R.format.name == 'FITS' ims = list(R) # == [im for im in R] assert len(ims) == 3 # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data, None) # no meta data support raises(RuntimeError, R.get_meta_data, 0) # no meta data support
def test_fits_reading(): """ Test reading fits """ need_internet() # We keep the fits files in the imageio-binary repo if IS_PYPY: return # no support for fits format :( simple = get_remote_file("images/simple.fits") multi = get_remote_file("images/multi.fits") # One image im = imageio.imread(simple) ims = imageio.mimread(simple) assert (im == ims[0]).all() assert len(ims) == 1 # Multiple images ims = imageio.mimread(multi) assert len(ims) == 3 R = imageio.read(multi) assert R.format.name == "FITS" ims = list(R) # == [im for im in R] assert len(ims) == 3 # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data, None) # no meta data support raises(RuntimeError, R.get_meta_data, 0) # no meta data support
def test_simpleitk_reading_writing(): """ Test reading and saveing tiff """ im2 = np.ones((10, 10, 3), np.uint8) * 2 filename1 = os.path.join(test_dir, 'test_tiff.tiff') # One image imageio.imsave(filename1, im2, 'itk') im = imageio.imread(filename1, 'itk') ims = imageio.mimread(filename1, 'itk') assert (im == im2).all() assert len(ims) == 1 # Mixed W = imageio.save(filename1, 'itk') raises(RuntimeError, W.set_meta_data, 1) assert W.format.name == 'ITK' W.append_data(im2) W.append_data(im2) W.close() # R = imageio.read(filename1, 'itk') assert R.format.name == 'ITK' ims = list(R) # == [im for im in R] assert (ims[0] == im2).all() # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data)
def test_lytro_raw_illum_reading(): """Test reading of lytro .raw file""" # Get test images need_internet() raw_file = get_remote_file(RAW_ILLUM_FILENAME) raw_meta_file = get_remote_file(RAW_ILLUM_META_FILENAME) # Read image and metadata file img = imageio.imread(raw_file, format="lytro-illum-raw") meta_gt = json.load(open(raw_meta_file)) # Test image shape and some pixel values # Pixel values are extracted from the Matlab reference implementation assert img.shape == (5368, 7728) assert round(img[24, 48], 15) == 0.738025415444770 assert round(img[3692, 86], 15) == 0.132942326490714 assert round(img[258, 1658], 15) == 0.687194525904203 assert round(img[1349, 6765], 15) == 0.113391984359726 assert round(img[210, 6761], 15) == 0.162267839687195 assert round(img[5231, 6459], 15) == 0.784946236559140 assert round(img[5213, 7477], 15) == 0.095796676441838 assert round(img[2745, 3789], 15) == 0.760508308895406 assert round(img[1428, 4192], 15) == 0.621700879765396 # Test extracted metadata against extracted metadata from .txt file assert img._meta == meta_gt # Test fail test_reader = imageio.read(raw_file, "lytro-illum-raw") raises(IndexError, test_reader.get_data, -1) raises(IndexError, test_reader.get_data, 3)
def test_lytro_raw_f0_reading(): """ Test reading of lytro .raw file """ # Get test images need_internet() raw_file = get_remote_file(RAW_F0_FILENAME) raw_meta_file = get_remote_file(RAW_F0_META_FILENAME) # Read image and metadata file img = imageio.imread(raw_file, format="lytro-f01-raw") meta_gt = json.load(open(raw_meta_file)) # Test image shape and some pixel values # Pixel values are extracted from the Matlab reference implementation assert img.shape == (3280, 3280) assert round(img[16, 7], 15) == 0.044688644688645 assert round(img[803, 74], 15) == 0.064713064713065 assert round(img[599, 321], 15) == 0.059340659340659 assert round(img[1630, 665], 15) == 0.198046398046398 assert round(img[940, 2030], 15) == 0.130647130647131 assert round(img[3164, 2031], 15) == 0.129914529914530 assert round(img[3235, 3250], 15) == 0.136019536019536 assert round(img[2954, 889], 15) == 0.159706959706960 assert round(img[1546, 1243], 15) == 0.227350427350427 # Test extracted metadata against extracted metadata from .txt file assert img._meta == meta_gt # Test fail test_reader = imageio.read(raw_file, "lytro-f01-raw") raises(IndexError, test_reader.get_data, -1) raises(IndexError, test_reader.get_data, 3)
def test_lytro_raw_f0_reading(): """Test reading of lytro .raw file""" # Get test images need_internet() raw_file = get_remote_file(RAW_F0_FILENAME) raw_meta_file = get_remote_file(RAW_F0_META_FILENAME) # Read image and metadata file img = imageio.imread(raw_file, format="lytro-f01-raw") meta_gt = json.load(open(raw_meta_file)) # Test image shape and some pixel values # Pixel values are extracted from the Matlab reference implementation assert img.shape == (3280, 3280) assert round(img[16, 7], 15) == 0.044688644688645 assert round(img[803, 74], 15) == 0.064713064713065 assert round(img[599, 321], 15) == 0.059340659340659 assert round(img[1630, 665], 15) == 0.198046398046398 assert round(img[940, 2030], 15) == 0.130647130647131 assert round(img[3164, 2031], 15) == 0.129914529914530 assert round(img[3235, 3250], 15) == 0.136019536019536 assert round(img[2954, 889], 15) == 0.159706959706960 assert round(img[1546, 1243], 15) == 0.227350427350427 # Test extracted metadata against extracted metadata from .txt file assert img._meta == meta_gt # Test fail test_reader = imageio.read(raw_file, "lytro-f01-raw") raises(IndexError, test_reader.get_data, -1) raises(IndexError, test_reader.get_data, 3)
def test_lytro_raw_illum_reading(): """ Test reading of lytro .raw file """ # Get test images need_internet() raw_file = get_remote_file(RAW_ILLUM_FILENAME) raw_meta_file = get_remote_file(RAW_ILLUM_META_FILENAME) # Read image and metadata file img = imageio.imread(raw_file, format="lytro-illum-raw") meta_gt = json.load(open(raw_meta_file)) # Test image shape and some pixel values # Pixel values are extracted from the Matlab reference implementation assert img.shape == (5368, 7728) assert round(img[24, 48], 15) == 0.738025415444770 assert round(img[3692, 86], 15) == 0.132942326490714 assert round(img[258, 1658], 15) == 0.687194525904203 assert round(img[1349, 6765], 15) == 0.113391984359726 assert round(img[210, 6761], 15) == 0.162267839687195 assert round(img[5231, 6459], 15) == 0.784946236559140 assert round(img[5213, 7477], 15) == 0.095796676441838 assert round(img[2745, 3789], 15) == 0.760508308895406 assert round(img[1428, 4192], 15) == 0.621700879765396 # Test extracted metadata against extracted metadata from .txt file assert img._meta == meta_gt # Test fail test_reader = imageio.read(raw_file, "lytro-illum-raw") raises(IndexError, test_reader.get_data, -1) raises(IndexError, test_reader.get_data, 3)
def read_video(filepath, frame_size): imageio_video = imageio.read(filepath) snap_length = len(imageio_video) frames = np.zeros((snap_length, 3, *frame_size)) resized = map(lambda frame: _resize_frame(frame, frame_size), imageio_video) for i, frame in enumerate(resized): frames[i, :, :, :] = frame return frames
def _count_frames(self): frame_lengths = np.array([len(imageio.read(p)) for p in self.video_paths]) self.frame_lengths = frame_lengths - OFFSET self.cumulative_lengths = np.zeros(len(self.frame_lengths), dtype=np.int32) prev = 0 for i, frames in enumerate(self.frame_lengths): prev = self.cumulative_lengths[i-1] self.cumulative_lengths[i] = prev + frames
def show_in_mpl(): reader = imageio.read('cockatoo.mp4', 'avbin') for i in range(10): reader.get_next_data() import pylab pylab.ion() pylab.show(reader.get_next_data())
def show_in_console(test_images): reader = imageio.read(test_images / "cockatoo.mp4", "ffmpeg") # reader = imageio.read('<video0>') im = reader.get_next_data() while True: im = reader.get_next_data() print("frame min/max/mean: %1.1f / %1.1f / %1.1f" % (im.min(), im.max(), (im.sum() / im.size)))
def show_in_console(): reader = imageio.read('cockatoo.mp4', 'ffmpeg') #reader = imageio.read('<video0>') im = reader.get_next_data() while True: im = reader.get_next_data() print('frame min/max/mean: %1.1f / %1.1f / %1.1f' % (im.min(), im.max(), (im.sum() / im.size)))
def convert(i): print(i) vid = imageio.read(i) for num, img in enumerate(vid.iter_data()): save_dir = i.split(".mp4")[0] save_dir = save_dir+ "_{}.jpg".format(num) img = Image.fromarray(img) img.save(save_dir)
def show(): reader = imageio.read(get_remote_file('images/cockatoo.mp4')) for i in range(10): reader.get_next_data() import pylab pylab.ion() pylab.show(reader.get_next_data())
def test_reader_more(): need_internet() fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname3 = fname1[:-4] + '.stub.mp4' # Get meta data R = imageio.read(fname1, 'ffmpeg', loop=True) meta = R.get_meta_data() assert len(R) == 280 assert isinstance(meta, dict) assert 'fps' in meta R.close() # Test size argument im = imageio.read(fname1, 'ffmpeg', size=(50, 50)).get_data(0) assert im.shape == (50, 50, 3) im = imageio.read(fname1, 'ffmpeg', size='40x40').get_data(0) assert im.shape == (40, 40, 3) raises(ValueError, imageio.read, fname1, 'ffmpeg', size=20) raises(ValueError, imageio.read, fname1, 'ffmpeg', pixelformat=20) # Read all frames and test length R = imageio.read(get_remote_file('images/realshort.mp4'), 'ffmpeg') count = 0 while True: try: R.get_next_data() except IndexError: break else: count += 1 assert count == len(R) assert count in (35, 36) # allow one frame off size that we know # Test index error -1 raises(IndexError, R.get_data, -1) # Now read beyond (simulate broken file) with raises(RuntimeError): R._read_frame() # ffmpeg seems to have an extra frame, avbin not? R._read_frame() # Test loop R = imageio.read(get_remote_file('images/realshort.mp4'), 'ffmpeg', loop=1) im1 = R.get_next_data() for i in range(1, len(R)): R.get_next_data() im2 = R.get_next_data() im3 = R.get_data(0) im4 = R.get_data(2) # touch skipping frames assert (im1 == im2).all() assert (im1 == im3).all() assert not (im1 == im4).all() R.close() # Read invalid open(fname3, 'wb') raises(IOError, imageio.read, fname3, 'ffmpeg') # Read printing info imageio.read(fname1, 'ffmpeg', print_info=True)
def json_to_sample(self, sample): asset = sample["asset"] data = np.asarray( *imageio.read(self.dir.joinpath(asset["name"]))).astype( np.float32) / 255 label = self.regions_to_label(sample["regions"], self.class_labels, data.shape) data = data.reshape((1, *data.shape)) return data, label.reshape((1, *label.shape))
def test_read_format(): # Set videofomat # Also set skipempty, so we can test mean reader = imageio.read(get_remote_file('images/cockatoo.mp4'), 'avbin', videoformat='mp4', skipempty=True) for i in range(10): im = reader.get_next_data() assert im.shape == (720, 1280, 3) assert mean(im) > 100 and mean(im) < 115
def set_videos(self, videofiles, videotimes = None): self.cv_image_widgets = [ ] self.grid_changing =False self.videofiles = videofiles self.videotimes = videotimes if self.videotimes is None: self.videotimes = [None]*len(videofiles) all = [ ] for i, vid in enumerate(self.videofiles): name = '{} {}'.format(i, os.path.basename(vid)) all.append({ 'name': name, 'type' : 'group', 'children' : param_by_channel}) self.paramVideos = pg.parametertree.Parameter.create(name='Videos', type='group', children=all) self.allParams = pg.parametertree.Parameter.create(name = 'all param', type = 'group', children = [self.paramGlobal,self.paramVideos ]) self.paramControler = VideoViewerControler(viewer = self) #~ self.captures = [ ] self.videos = [ ] self.video_length = [ ] self.video_fps = [ ] for i, vid in enumerate(self.videofiles): #~ cap = cv2.VideoCapture(vid) #~ self.captures.append(cap) #~ self.video_length.append(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) #~ self.video_fps.append(cap.get(cv2.cv.CV_CAP_PROP_FPS)) if mode =='imageio': #~ v = imageio.get_reader(vid, format = 'avi', mode = 'I') #~ v = imageio.read(vid, 'avbin') v = imageio.read(vid, 'ffmpeg') self.videos.append(v) self.video_length.append(v.get_meta_data()['nframes']) self.video_fps.append(v.get_meta_data()['fps']) elif mode =='skimage': #~ v = skimage.io.Video(source = vid, backend = 'gstreamer') v = skimage.io.Video(source = vid, backend = 'opencv') self.videos.append(v) self.video_length.append(v.frame_count()) #~ self.video_fps.append(25.) self.video_fps.append(float(v.duration())/v.frame_count()) #~ print self.video_fps, self.video_length self.create_grid() self.paramVideos.sigTreeStateChanged.connect(self.create_grid) self.paramGlobal.param('nb_column').sigValueChanged.connect(self.create_grid) self.proxy = pg.SignalProxy(self.allParams.sigTreeStateChanged, rateLimit=5, delay=0.1, slot=self.refresh)
def img2gif(img_path="out/dcgan/", gif_path="out/dcgan/"): #获取图像文件列表 file_list = os.listdir(img_path) imges = [] for file in file_list: if file.endswith(".png"): img_name = img_path + file imges.append(imageio.read(img_name)) imageio.mimsave(gif_path + "result.gif", imges, fps=2)
def test_read_and_write(): fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname2 = fname1[:-4] + '.out.mp4' # Read ims1 = [] with imageio.read(fname1, 'ffmpeg') as R: for i in range(10): im = R.get_next_data() ims1.append(im) assert im.shape == (720, 1280, 3) assert im.sum() > 0 # Seek im = R.get_data(120) assert im.shape == (720, 1280, 3) # Save with imageio.save(fname2, 'ffmpeg') as W: for im in ims1: W.append_data(im) # Read the result ims2 = imageio.mimread(fname2, 'ffmpeg') assert len(ims1) == len(ims2) # Check for im1, im2 in zip(ims1, ims2): diff = np.abs(im1.astype(np.float32) - im2.astype(np.float32)) assert diff.mean() < 2.0 # Check loop R = imageio.read(fname2, 'ffmpeg', loop=True) im1 = R.get_next_data() for i in range(1, len(R)): R.get_next_data() im2 = R.get_next_data() im3 = R.get_data(0) im4 = R.get_data(2) # touch skipping frames assert (im1 == im2).all() assert (im1 == im3).all() assert not (im1 == im4).all() R.close()
def convertScreenFramesToVideo(sourceFolder, destPath): fileNames = listdir(sourceFolder) fileNames.sort() writer = get_writer(destPath, fps=24) for name in fileNames: currentImage = read(sourceFolder + name) currentFrame = currentImage.get_data(0) writer.append_data(currentFrame) writer.close()
def test_webcam(): good_paths = ["<video0>", "<video42>"] for path in good_paths: # regression test for https://github.com/imageio/imageio/issues/676 tmp_request = imageio.core.Request(path, "rI") assert imageio.formats["ffmpeg"].can_read(tmp_request) tmp_request.finish() try: imageio.read(path, format="ffmpeg") except IndexError: # IndexError should be raised when # path string is good but camera doesnt exist continue bad_paths = ["<videof1>", "<video0x>", "<video>"] for path in bad_paths: with raises(ValueError, match=".*Could not find a format to read.*"): imageio.read(path)
def show(): reader = imageio.read('<video0>') import visvis as vv im = reader.get_next_data() t = vv.imshow(im) while True: t.SetData(reader.get_next_data()) vv.processEvents()
def test_format_selection(test_images): fname1 = test_images / "stent.swf" fname2 = fname1.with_suffix(".out.swf") F = imageio.formats["swf"] assert F.name == "SWF" assert type(imageio.formats[".swf"]) is type(F) assert type(imageio.read(fname1).format) is type(F) assert type(imageio.save(fname2).format) is type(F)
def test_format_selection(): fname1 = get_remote_file('images/stent.swf', test_dir) fname2 = fname1[:-4] + '.out.swf' F = imageio.formats['swf'] assert F.name == 'SWF' assert imageio.formats['.swf'] is F assert imageio.read(fname1).format is F assert imageio.save(fname2).format is F
def write_video(input_video_path, data_dir, tracab_id, params, event_telemetry, video_metadata): start_frame = params[0] end_frame = params[1] fps = 25 output_dir = os.path.join(data_dir, tracab_id, "vid_files") if not os.path.exists(output_dir): os.mkdir(output_dir) out = cv2.VideoWriter(os.path.join(output_dir, "tracklets.avi"), \ cv2.VideoWriter_fourcc('m', 'p', '4', '2'), fps, (1920, 480), 1) traj_files = os.path.join(data_dir, tracab_id, "trajectory_files") num_frames = end_frame - start_frame + 1 video = imageio.read(input_video_path) projection_line = video_metadata['MediaproPanaMetaData']['match'][ 'videofile']['projection']['@matrix'] projection_matrix = np.array(map(float, projection_line.split())).reshape(3, 4) for frame in range(0, num_frames): img = get_video(video, start_frame + frame, event_telemetry, video_metadata) colors = [(255, 0, 0), \ (255, 255, 0), \ (255, 255, 255), \ (0, 255, 0), \ (0, 255, 255), (0, 0, 255)] count = 0 for file in os.listdir(traj_files): positions = get_positions_file(os.path.join(traj_files, file)) for i in range(0, frame + 1): projections = project(np.array([positions[i]]), projection_matrix, z=1.82 / 2) cv2.rectangle( img, (int(projections[0][0]), int(projections[0][1])), (int(projections[0][0] + 1), int(projections[0][1] + 1)), colors[count], 2) count = count + 1 if count >= len(colors): count = 0 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) out.write(img) out.release()
def test_npz_reading_writing(): """ Test reading and saveing npz """ if IS_PYPY: return # no support for npz format :( im2 = np.ones((10, 10), np.uint8) * 2 im3 = np.ones((10, 10, 10), np.uint8) * 3 im4 = np.ones((10, 10, 10, 10), np.uint8) * 4 filename1 = os.path.join(test_dir, 'test_npz.npz') # One image imageio.imsave(filename1, im2) im = imageio.imread(filename1) ims = imageio.mimread(filename1) assert (im == im2).all() assert len(ims) == 1 # Multiple images imageio.mimsave(filename1, [im2, im2, im2]) im = imageio.imread(filename1) ims = imageio.mimread(filename1) assert (im == im2).all() assert len(ims) == 3 # Volumes imageio.mvolsave(filename1, [im3, im3]) im = imageio.volread(filename1) ims = imageio.mvolread(filename1) assert (im == im3).all() assert len(ims) == 2 # Mixed W = imageio.save(filename1) assert W.format.name == 'NPZ' W.append_data(im2) W.append_data(im3) W.append_data(im4) raises(RuntimeError, W.set_meta_data, {}) # no meta data support W.close() # R = imageio.read(filename1) assert R.format.name == 'NPZ' ims = list(R) # == [im for im in R] assert (ims[0] == im2).all() assert (ims[1] == im3).all() assert (ims[2] == im4).all() # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) raises(RuntimeError, R.get_meta_data, None) # no meta data support raises(RuntimeError, R.get_meta_data, 0) # no meta data support
def test_read(): reader = imageio.read(get_remote_file('images/cockatoo.mp4')) assert reader.get_length() == np.inf reader.get_meta_data() reader.format.can_save(core.Request('test.mp4', 'wI')) for i in range(10): mean = reader.get_next_data().mean() assert mean > 100 and mean < 115 with raises(IndexError): reader.get_data(0)
def test_tifffile_reading_writing(): """ Test reading and saving tiff """ need_internet() # We keep a test image in the imageio-binary repo im2 = np.ones((10, 10, 3), np.uint8) * 2 filename1 = os.path.join(test_dir, 'test_tiff.tiff') # One image imageio.imsave(filename1, im2) im = imageio.imread(filename1) ims = imageio.mimread(filename1) assert (im == im2).all() assert len(ims) == 1 # Multiple images imageio.mimsave(filename1, [im2, im2, im2]) im = imageio.imread(filename1) ims = imageio.mimread(filename1) assert (im == im2).all() assert len(ims) == 3, ims[0].shape # remote multipage rgb file filename2 = get_remote_file('images/multipage_rgb.tif') img = imageio.mimread(filename2) assert len(img) == 2 assert img[0].shape == (3, 10, 10) # Mixed W = imageio.save(filename1) W.set_meta_data({'planarconfig': 'planar'}) assert W.format.name == 'TIFF' W.append_data(im2) W.append_data(im2) W.close() # R = imageio.read(filename1) assert R.format.name == 'TIFF' ims = list(R) # == [im for im in R] assert (ims[0] == im2).all() meta = R.get_meta_data() assert meta['orientation'] == 'top_left' # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) # Ensure imwrite write works round trip filename3 = os.path.join(test_dir, 'test_tiff2.tiff') R = imageio.imread(filename1) imageio.imwrite(filename3, R) R2 = imageio.imread(filename3) assert (R == R2).all()
def test_different_read_modes_with_readers(): dname1, dname2, fname1, fname2 = _prepare() for fname, dname, n in [(fname1, dname1, 1), (fname2, dname2, 2)]: # Test imread() R = imageio.read(fname, 'DICOM', 'i') assert len(R) == 1 assert isinstance(R.get_meta_data(), dict) assert isinstance(R.get_meta_data(0), dict) # Test mimread() R = imageio.read(fname, 'DICOM', 'I') if n == 1: assert len(R) > 10 else: assert len(R) == 20 + 25 assert isinstance(R.get_meta_data(), dict) assert isinstance(R.get_meta_data(0), dict) # Test volread() R = imageio.read(fname, 'DICOM', 'v') assert len(R) == n # we ask for one, but get an honest number assert isinstance(R.get_meta_data(), dict) assert isinstance(R.get_meta_data(0), dict) # Test mvolread() R = imageio.read(fname, 'DICOM', 'V') assert len(R) == n assert isinstance(R.get_meta_data(), dict) assert isinstance(R.get_meta_data(0), dict) # Touch DicomSeries objects assert repr(R._series[0]) assert R._series[0].description assert len(R._series[0].sampling) == 3 R = imageio.read(fname, 'DICOM', '?') raises(RuntimeError, R.get_length)
def show_in_visvis(): reader = imageio.read('cockatoo.mp4', 'ffmpeg') #reader = imageio.read('<video0>') import visvis as vv im = reader.get_next_data() f = vv.clf() f.title = reader.format.name t = vv.imshow(im, clim=(0, 255)) while not f._destroyed: t.SetData(reader.get_next_data()) vv.processEvents()
def test_read_and_write(): need_internet() R = imageio.read(get_remote_file('images/cockatoo.mp4'), 'ffmpeg') assert R.format is imageio.formats['ffmpeg'] fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname2 = fname1[:-4] + '.out.mp4' # Read ims1 = [] with imageio.read(fname1, 'ffmpeg') as R: for i in range(10): im = R.get_next_data() ims1.append(im) assert im.shape == (720, 1280, 3) assert (im.sum() / im.size) > 0 # pypy mean is broken assert im.sum() > 0 # Seek im = R.get_data(120) assert im.shape == (720, 1280, 3) # Save with imageio.save(fname2, 'ffmpeg') as W: for im in ims1: W.append_data(im) # Read the result ims2 = imageio.mimread(fname2, 'ffmpeg') assert len(ims1) == len(ims2) # Check for im1, im2 in zip(ims1, ims2): diff = np.abs(im1.astype(np.float32) - im2.astype(np.float32)) if IS_PYPY: assert (diff.sum() / diff.size) < 100 else: assert diff.mean() < 2.5
def test_format_selection(): need_internet() fname1 = get_remote_file("images/stent.swf", test_dir) fname2 = fname1[:-4] + ".out.swf" F = imageio.formats["swf"] assert F.name == "SWF" assert imageio.formats[".swf"] is F assert imageio.read(fname1).format is F assert imageio.save(fname2).format is F