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_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 write_gif_with_image_io(clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar"): """Writes the gif with the Python library ImageIO (calls FreeImage).""" if colors is None: colors = 256 logger = proglog.default_bar_logger(logger) if not IMAGEIO_FOUND: raise ImportError( "Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else "nq" writer = imageio.save(filename, duration=1.0 / fps, quantizer=quantizer, palettesize=colors, loop=loop) logger(message="MoviePy - Building file %s with imageio." % filename) for frame in clip.iter_frames(fps=fps, logger=logger, dtype="uint8"): writer.append_data(frame)
def write_gif_with_image_io(clip, filename, fps=None, opt='wu', loop=0, colors=None, verbose=True): """ Writes the gif with the Python library ImageIO (calls FreeImage). For the moment ImageIO is not installed with CartoonPy. You need to install imageio (pip install imageio) to use this. Parameters ----------- opt """ if colors is None: colors=256 if not IMAGEIO_FOUND: raise ImportError("Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") if fps is None: fps = clip.fps quantizer = 'wu' if opt!= 'nq' else 'nq' writer = imageio.save(filename, duration=1.0/fps, quantizer=quantizer, palettesize=colors) verbose_print(verbose, "\n[CartoonPy] Building file %s with imageio\n"%filename) for frame in clip.iter_frames(fps=fps, progress_bar=True, dtype='uint8'): writer.append_data(frame)
def write_gif_with_image_io(clip, filename, fps=None, opt="wu", loop=0, colors=None, verbose=True): """ Writes the gif with the Python library ImageIO (calls FreeImage). For the moment ImageIO is not installed with MoviePy. You need to install imageio (pip install imageio) to use this. Parameters ----------- opt """ if colors is None: colors = 256 if not IMAGEIO_FOUND: raise ImportError("Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") if fps is None: fps = clip.fps quantizer = "wu" if opt != "nq" else "nq" writer = imageio.save(filename, duration=1.0 / fps, quantizer=quantizer, palettesize=colors) verbose_print(verbose, "\n[MoviePy] Building file %s with imageio\n" % filename) for frame in clip.iter_frames(fps=fps, progress_bar=True, dtype="uint8"): writer.append_data(frame)
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_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_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 write_gif_with_image_io(clip, filename, fps=None, opt=0, loop=0, colors=None, verbose=True, progress_bar=True, progress_cb=None): """ Writes the gif with the Python library ImageIO (calls FreeImage). Parameters ----------- opt progress_bar Boolean indicating whether to display a progress bar in the terminal while exporting the file. progress_cb Callback function to call during export. It should accept the current frame index being exported and the total number of frames. It can be used to update a gui progressbar while running in a separate thread. """ if colors is None: colors = 256 if not IMAGEIO_FOUND: raise ImportError("Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else 'nq' writer = imageio.save( filename, duration=1.0/fps, quantizer=quantizer, palettesize=colors, loop=loop ) verbose_print(verbose, "\n[MoviePy] Building file %s with imageio\n" % filename) # if progress callback was define, call it if callable(progress_cb): nframes = int(clip.duration*fps)+1 count = 1 for frame in clip.iter_frames(fps=fps, progress_bar=progress_bar, dtype='uint8'): writer.append_data(frame) # if progress callback was define, call it if callable(progress_cb): progress_cb(count, nframes) count += 1
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_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 make_gif_kegg(path_id, entry_items, color_list, label_list=None, etype ='gene'): pathway_image, content_xml = get_req_xml_kegg(path_id) entity_graphic_dict = parse_entitys_dict(get_xml_element_of_kegg(content_xml)) target_list = [i for i in \ extract_graphic_entity(entry_items, color_list, entity_graphic_dict, etype, label_list)] del entity_graphic_dict movie = imageio.save(path_id + '.gif', fps=25) gif_make(movie, pathway_image, target_list, duration=13) del movie
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_tifffile_reading_writing(): """ Test reading and saveing 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['is_rgb'] # 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_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_npz_reading_writing(tmp_path): """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 = tmp_path / "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) pytest.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 pytest.raises(IndexError, R.get_data, -1) pytest.raises(IndexError, R.get_data, 3) pytest.raises(RuntimeError, R.get_meta_data, None) # no meta data support pytest.raises(RuntimeError, R.get_meta_data, 0) # no meta data support
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
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 test_writer_more(): fname1 = get_remote_file('images/cockatoo.mp4', test_dir) fname2 = fname1[:-4] + '.out.mp4' W = imageio.save(fname2, 'ffmpeg') with raises(ValueError): # Invalid shape W.append_data(np.zeros((20, 20, 5), np.uint8)) W.append_data(np.zeros((20, 20, 3), np.uint8)) with raises(ValueError): # Different shape from first image W.append_data(np.zeros((20, 19, 3), np.uint8)) with raises(ValueError): # Different depth from first image W.append_data(np.zeros((20, 20, 4), np.uint8)) with raises(RuntimeError): # No meta data W.set_meta_data({'foo': 3}) W.close()
def test_writer_more(): fname1 = get_remote_file("images/cockatoo.mp4", test_dir) fname2 = fname1[:-4] + ".out.mp4" W = imageio.save(fname2, "ffmpeg") with raises(ValueError): # Invalid shape W.append_data(np.zeros((20, 20, 5), np.uint8)) W.append_data(np.zeros((20, 20, 3), np.uint8)) with raises(ValueError): # Different shape from first image W.append_data(np.zeros((20, 19, 3), np.uint8)) with raises(ValueError): # Different depth from first image W.append_data(np.zeros((20, 20, 4), np.uint8)) with raises(RuntimeError): # No meta data W.set_meta_data({"foo": 3}) W.close()
def test_writer_more(test_images): fname1 = test_images / "cockatoo.mp4" fname2 = fname1.with_suffix(".out.mp4") W = imageio.save(fname2, "ffmpeg") with pytest.raises(ValueError): # Invalid shape W.append_data(np.zeros((20, 20, 5), np.uint8)) W.append_data(np.zeros((20, 20, 3), np.uint8)) with pytest.raises(ValueError): # Different shape from first image W.append_data(np.zeros((20, 19, 3), np.uint8)) with pytest.raises(ValueError): # Different depth from first image W.append_data(np.zeros((20, 20, 4), np.uint8)) with pytest.raises(RuntimeError): # No meta data W.set_meta_data({"foo": 3}) W.close()
def test_ico(): if os.getenv("TRAVIS", "") == "true" and sys.version_info >= (3, 4): skip("Freeimage ico is unstable for this Travis build") for float in (False, True): for crop in (0,): for colors in (1, 3, 4): fname = fnamebase + "%i.%i.%i.ico" % (float, crop, colors) rim = get_ref_im(colors, crop, float) rim = rim[:32, :32] # ico needs nice size 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.1.ico") assert isinstance(R.get_meta_data(0), dict) assert isinstance(R.get_meta_data(None), dict) # But this print warning R.close() 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.1.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) if sys.platform.startswith("win"): # issue #21 skip("Windows has a known issue with multi-icon files") # Multiple images im = get_ref_im(4, 0, 0)[:32, :32] ims = [np.repeat(np.repeat(im, i, 1), i, 0) for i in (1, 2)] # SegF on win ims = im, np.column_stack((im, im)), np.row_stack((im, im)) # error on win imageio.mimsave(fnamebase + "I2.ico", ims) ims2 = imageio.mimread(fnamebase + "I2.ico") for im1, im2 in zip(ims, ims2): assert_close(im1, im2, 0.1)
def test_ico(setup_library, tmp_path): fnamebase = str(tmp_path / "test") for isfloat in (False, True): for crop in (0, ): for colors in (1, 3, 4): fname = fnamebase + "%i.%i.%i.ico" % (isfloat, crop, colors) rim = get_ref_im(colors, crop, isfloat) rim = rim[:32, :32] # ico needs nice size imageio.imsave(fname, rim, format="ICO-FI") im = imageio.imread(fname, format="ICO-FI") mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless # Meta data R = imageio.read(fnamebase + "0.0.1.ico", format="ICO-FI") assert isinstance(R.get_meta_data(0), dict) assert isinstance(R.get_meta_data(None), dict) # But this print warning R.close() writer = imageio.save(fnamebase + "I.ico", format="ICO-FI") writer.set_meta_data({}) writer.close() # Parameters. Note that with makealpha, RGBA images are read in incorrectly im = imageio.imread(fnamebase + "0.0.1.ico", makealpha=True, format="ICO-FI") assert im.ndim == 3 and im.shape[-1] == 4 # Parameter fail raises(TypeError, imageio.imread, fname, notavalidkwarg=True, format="ICO-FI") raises( TypeError, imageio.imsave, fnamebase + "1.ico", im, notavalidk=True, format="ICO-FI", )
def test_ico(): if os.getenv('TRAVIS', '') == 'true' and sys.version_info >= (3, 4): skip('Freeimage ico is unstable for this Travis build') for isfloat in (False, True): for crop in (0, ): for colors in (1, 3, 4): fname = fnamebase + '%i.%i.%i.ico' % (isfloat, crop, colors) rim = get_ref_im(colors, crop, isfloat) rim = rim[:32, :32] # ico needs nice size imageio.imsave(fname, rim) im = imageio.imread(fname) mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless # Meta data R = imageio.read(fnamebase + '0.0.1.ico') assert isinstance(R.get_meta_data(0), dict) assert isinstance(R.get_meta_data(None), dict) # But this print warning R.close() 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.1.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) if sys.platform.startswith('win'): # issue #21 skip('Windows has a known issue with multi-icon files') # Multiple images im = get_ref_im(4, 0, 0)[:32, :32] ims = [np.repeat(np.repeat(im, i, 1), i, 0) for i in (1, 2)] # SegF on win ims = im, np.column_stack((im, im)), np.row_stack((im, im)) # error on win imageio.mimsave(fnamebase + 'I2.ico', ims) ims2 = imageio.mimread(fnamebase + 'I2.ico') for im1, im2 in zip(ims, ims2): assert_close(im1, im2, 0.1)
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 convert(filename, resolution, fps, filetype): """ Converts a recorded .golf file into a video. """ print(f'Converting {filename}...') with imageio.save(f'{filename.replace(GOLFR_EXTENSION, "")}.{filetype}', fps=fps) as writer: with open(filename, mode='r') as f: lines = f.readlines() if len(lines) < 2: print(f"Error detected in {filename}") return size = int(lines[0]) image = np.empty(size * size, dtype=np.uint8) for line in tqdm(lines): image.fill(255) image[np.fromstring(line, dtype=np.int32, sep=',')] = 0 writer.append_data( np.repeat(np.repeat(image.reshape((size, size)), resolution, axis=1), resolution, axis=0) )
def test_tifffile_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) 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["is_rgb"] # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3)
def test_ico(): for float in (False, True): for crop in (0, 1, 2): for colors in (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.1.ico') assert isinstance(R.get_meta_data(0), dict) assert isinstance(R.get_meta_data(None), dict) # But this print warning R.close() 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.1.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) if sys.platform.startswith('win'): # issue #21 skip('Windows has a known issue with multi-icon files') # Multiple images im = get_ref_im(4, 0, 0) ims = [np.repeat(np.repeat(im, i, 1), i, 0) for i in (1, 2)] # SegF on win ims = im, np.column_stack((im, im)), np.row_stack((im, im)) # error on win imageio.mimsave(fnamebase + 'I2.ico', ims) ims2 = imageio.mimread(fnamebase + 'I2.ico') for im1, im2 in zip(ims, ims2): assert_close(im1, im2, 0.1)
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 write_gif_with_image_io(clip, filename, fps=None, opt=0, loop=0, colors=None, verbose=True, logger='bar'): """ Writes the gif with the Python library ImageIO (calls FreeImage). Parameters ----------- opt """ if colors is None: colors = 256 logger = proglog.default_bar_logger(logger) if not IMAGEIO_FOUND: error = ImportError("Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") logger.error(error) raise error if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else 'nq' writer = imageio.save( filename, duration=1.0/fps, quantizer=quantizer, palettesize=colors, loop=loop ) logger.info(msg='MoviePy - Building file %s with imageio.' % filename) for frame in clip.iter_frames(fps=fps, logger=logger, dtype='uint8'): writer.append_data(frame)
def write_gif_with_image_io(clip, filename, fps=None, opt=0, loop=0, colors=None, verbose=True, logger='bar'): """ Writes the gif with the Python library ImageIO (calls FreeImage). Parameters ----------- opt """ if colors is None: colors = 256 logger = proglog.default_bar_logger(logger) if not IMAGEIO_FOUND: raise ImportError("Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'") if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else 'nq' writer = imageio.save( filename, duration=1.0/fps, quantizer=quantizer, palettesize=colors, loop=loop ) logger(message='MoviePy - Building file %s with imageio.' % filename) for frame in clip.iter_frames(fps=fps, logger=logger, dtype='uint8'): writer.append_data(frame)
def test_functions(): """ Test the user-facing API functions """ # Test help(), it prints stuff, so we just check whether that goes ok imageio.help() # should print overview imageio.help("PNG") # should print about PNG fname1 = get_remote_file("images/chelsea.png", test_dir) fname2 = fname1[:-3] + "jpg" fname3 = fname1[:-3] + "notavalidext" open(fname3, "wb") # Test read() R1 = imageio.read(fname1) R2 = imageio.read(fname1, "png") assert R1.format is R2.format # Fail raises(ValueError, imageio.read, fname3) # existing but not readable raises(FileNotFoundError, imageio.read, "notexisting.barf") raises(IndexError, imageio.read, fname1, "notexistingformat") # Test save() W1 = imageio.save(fname2) W2 = imageio.save(fname2, "JPG") W1.close() W2.close() assert W1.format is W2.format # Fail raises(FileNotFoundError, imageio.save, "~/dirdoesnotexist/wtf.notexistingfile") # Test imread() im1 = imageio.imread(fname1) im2 = imageio.imread(fname1, "png") assert im1.shape[2] == 3 assert np.all(im1 == im2) # Test imsave() if os.path.isfile(fname2): os.remove(fname2) assert not os.path.isfile(fname2) imageio.imsave(fname2, im1[:, :, 0]) imageio.imsave(fname2, im1) assert os.path.isfile(fname2) # Test mimread() fname3 = get_remote_file("images/newtonscradle.gif", test_dir) ims = imageio.mimread(fname3) assert isinstance(ims, list) assert len(ims) > 1 assert ims[0].ndim == 3 assert ims[0].shape[2] in (1, 3, 4) # Test protection with raises(RuntimeError): imageio.mimread("imageio:chelsea.png", "dummy", length=np.inf) if IS_PYPY: return # no support for npz format :( # Test mimsave() fname5 = fname3[:-4] + "2.npz" if os.path.isfile(fname5): os.remove(fname5) assert not os.path.isfile(fname5) imageio.mimsave(fname5, [im[:, :, 0] for im in ims]) imageio.mimsave(fname5, ims) assert os.path.isfile(fname5) # Test volread() fname4 = get_remote_file("images/stent.npz", test_dir) vol = imageio.volread(fname4) assert vol.ndim == 3 assert vol.shape[0] == 256 assert vol.shape[1] == 128 assert vol.shape[2] == 128 # Test volsave() volc = np.zeros((10, 10, 10, 3), np.uint8) # color volume fname6 = os.path.join(test_dir, "images", "stent2.npz") if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.volsave(fname6, volc) imageio.volsave(fname6, vol) assert os.path.isfile(fname6) # Test mvolread() vols = imageio.mvolread(fname4) assert isinstance(vols, list) assert len(vols) == 1 assert vols[0].shape == vol.shape # Test mvolsave() if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.mvolsave(fname6, [volc, volc]) imageio.mvolsave(fname6, vols) assert os.path.isfile(fname6) # Fail for save functions raises(ValueError, imageio.imsave, fname2, np.zeros((100, 100, 5))) raises(ValueError, imageio.imsave, fname2, 42) raises(ValueError, imageio.mimsave, fname5, [np.zeros((100, 100, 5))]) raises(ValueError, imageio.mimsave, fname5, [42]) raises(ValueError, imageio.volsave, fname6, np.zeros((100, 100, 100, 40))) raises(ValueError, imageio.volsave, fname6, 42) raises(ValueError, imageio.mvolsave, fname6, [np.zeros((90, 90, 90, 40))]) raises(ValueError, imageio.mvolsave, fname6, [42])
def save_normal_map(cls, normal_map, path): """ TO BE REMOVED """ imageio.save(path, normal_map)
def test_reading_saving(): need_internet() fname1 = get_remote_file('images/stent.swf', test_dir) fname2 = fname1[:-4] + '.out.swf' fname3 = fname1[:-4] + '.compressed.swf' fname4 = fname1[:-4] + '.out2.swf' # Read R = imageio.read(fname1) assert len(R) == 10 assert R.get_meta_data() == {} # always empty dict ims1 = [] for im in R: assert im.shape == (657, 451, 4) assert mean(im) > 0 ims1.append(im) # Seek assert (R.get_data(3) == ims1[3]).all() # Fails raises(IndexError, R.get_data, -1) # No negative index raises(IndexError, R.get_data, 10) # Out of bounds R.close() # Test loop R = imageio.read(fname1, loop=True) assert (R.get_data(10) == ims1[0]).all() # setting meta data is ignored W = imageio.save(fname2) W.set_meta_data({'foo': 3}) W.close() # Write and re-read, now without loop, and with html page imageio.mimsave(fname2, ims1, loop=False, html=True) ims2 = imageio.mimread(fname2) # Check images. We can expect exact match, since # SWF is lossless. assert len(ims1) == len(ims2) for im1, im2 in zip(ims1, ims2): assert (im1 == im2).all() # Test compressed imageio.mimsave(fname3, ims2, compress=True) ims3 = imageio.mimread(fname3) assert len(ims1) == len(ims3) for im1, im3 in zip(ims1, ims3): assert (im1 == im3).all() # Test conventional, Bonus, we don't officially support this. _swf = imageio.plugins.swf.load_lib() _swf.write_swf(fname4, ims1) ims4 = _swf.read_swf(fname4) assert len(ims1) == len(ims4) for im1, im4 in zip(ims1, ims4): assert (im1 == im4).all() # We want to manually validate that this file plays in 3d party tools # So we write a small HTML5 doc that we can load html = """<!DOCTYPE html> <html> <body> Original: <embed src="%s"> <br ><br > Written: <embed src="%s"> <br ><br > Compressed: <embed src="%s"> <br ><br > Written 2: <embed src="%s"> </body> </html> """ % (fname1, fname2, fname3, fname4) with open(os.path.join(test_dir, 'test_swf.html'), 'wb') as f: for line in html.splitlines(): f.write(line.strip().encode('utf-8') + b'\n')
def test_animated_gif(): # Read newton's cradle ims = imageio.mimread("imageio:newtonscradle.gif") assert len(ims) == 36 for im in ims: assert im.shape == (150, 200, 4) assert im.min() > 0 assert im.max() <= 255 # 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 isfloat in (False, True): for colors in (3, 4): ims1 = ims[:] if isfloat: 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 print("fooo", fname, isfloat, colors) 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, fps=20) R = imageio.read(fnamebase + ".animated.loop2.gif") W = imageio.save(fnamebase + ".animated.palettes100.gif", palettesize=100) assert W._writer.opt_palette_size == 128 # Fail assert raises(IndexError, R.get_meta_data, -1) assert raises(ValueError, imageio.mimsave, fname, ims, palettesize=300) assert raises(ValueError, imageio.mimsave, fname, ims, quantizer="foo") assert raises(ValueError, imageio.mimsave, fname, ims, duration="foo") # Add one duplicate image to ims to touch subractangle with not change ims.append(ims[-1]) # 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 {}) imageio.mimsave(fname, [x[:, :, 0] for x in ims], duration=0.2) assert isinstance(imageio.read(fname).get_meta_data(), dict)
def test_functions(): """ Test the user-facing API functions """ # Test help(), it prints stuff, so we just check whether that goes ok imageio.help() # should print overview imageio.help('PNG') # should print about PNG fname1 = get_remote_file('images/chelsea.png', test_dir) fname2 = fname1[:-3] + 'jpg' fname3 = fname1[:-3] + 'notavalidext' open(fname3, 'wb') # Test read() R1 = imageio.read(fname1) R2 = imageio.read(fname1, 'png') assert R1.format is R2.format # Fail raises(ValueError, imageio.read, fname3) # existing but not readable raises(IOError, imageio.read, 'notexisting.barf') raises(IndexError, imageio.read, fname1, 'notexistingformat') # Test save() W1 = imageio.save(fname2) W2 = imageio.save(fname2, 'JPG') assert W1.format is W2.format # Fail raises(ValueError, imageio.save, 'wtf.notexistingfile') # Test imread() im1 = imageio.imread(fname1) im2 = imageio.imread(fname1, 'png') assert im1.shape[2] == 3 assert np.all(im1 == im2) # Test imsave() if os.path.isfile(fname2): os.remove(fname2) assert not os.path.isfile(fname2) imageio.imsave(fname2, im1[:, :, 0]) imageio.imsave(fname2, im1) assert os.path.isfile(fname2) # Test mimread() fname3 = get_remote_file('images/newtonscradle.gif', test_dir) ims = imageio.mimread(fname3) assert isinstance(ims, list) assert len(ims) > 1 assert ims[0].ndim == 3 assert ims[0].shape[2] in (1, 3, 4) if IS_PYPY: return # no support for npz format :( # Test mimsave() fname5 = fname3[:-4] + '2.npz' if os.path.isfile(fname5): os.remove(fname5) assert not os.path.isfile(fname5) imageio.mimsave(fname5, [im[:, :, 0] for im in ims]) imageio.mimsave(fname5, ims) assert os.path.isfile(fname5) # Test volread() fname4 = get_remote_file('images/stent.npz', test_dir) vol = imageio.volread(fname4) assert vol.ndim == 3 assert vol.shape[0] == 256 assert vol.shape[1] == 128 assert vol.shape[2] == 128 # Test volsave() volc = np.zeros((10, 10, 10, 3), np.uint8) # color volume fname6 = fname4[:-4] + '2.npz' if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.volsave(fname6, volc) imageio.volsave(fname6, vol) assert os.path.isfile(fname6) # Test mvolread() vols = imageio.mvolread(fname4) assert isinstance(vols, list) assert len(vols) == 1 assert vols[0].shape == vol.shape # Test mvolsave() if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.mvolsave(fname6, [volc, volc]) imageio.mvolsave(fname6, vols) assert os.path.isfile(fname6) # Fail for save functions raises(ValueError, imageio.imsave, fname2, np.zeros((100, 100, 5))) raises(ValueError, imageio.imsave, fname2, 42) raises(ValueError, imageio.mimsave, fname5, [np.zeros((100, 100, 5))]) raises(ValueError, imageio.mimsave, fname5, [42]) raises(ValueError, imageio.volsave, fname4, np.zeros((100, 100, 100, 40))) raises(ValueError, imageio.volsave, fname4, 42) raises(ValueError, imageio.mvolsave, fname4, [np.zeros((90, 90, 90, 40))]) raises(ValueError, imageio.mvolsave, fname4, [42])
def test_animated_gif(): if sys.platform.startswith('darwin'): skip('On OSX quantization of freeimage is unstable') # 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 isfloat in (False, True): for colors in (3, 4): ims1 = ims[:] if isfloat: 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, fps=20) 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') # Add one duplicate image to ims to touch subractangle with not change ims.append(ims[-1]) # 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_functions(test_images, tmp_path): """Test the user-facing API functions""" # Test help(), it prints stuff, so we just check whether that goes ok imageio.help() # should print overview imageio.help("PNG") # should print about PNG fname1 = test_images / "chelsea.png" fname2 = tmp_path / fname1.with_suffix(".jpg").name fname3 = tmp_path / fname1.with_suffix(".notavalidext").name open(fname3, "wb") # Test read() R1 = imageio.read(fname1) R2 = imageio.read(fname1, "png") # this tests if the highest priority png plugin and the highest # priority fallback plugin match. # Do we really what to enforce this? assert type(R1) is type(R2) raises(ValueError, imageio.read, fname3) # existing but not readable raises(IndexError, imageio.read, fname1, "notexistingformat") # Note: This is actually a test of Requests. We should probably # migrate or remove it. raises(FileNotFoundError, imageio.read, "notexisting.barf") # Test save() W1 = imageio.save(fname2) W2 = imageio.save(fname2, "JPG") W1.close() W2.close() assert type(W1) is type(W2) # Fail raises(FileNotFoundError, imageio.save, "~/dirdoesnotexist/wtf.notexistingfile") # Test imread() im1 = imageio.imread(fname1) im2 = imageio.imread(fname1, "png") assert im1.shape[2] == 3 assert np.all(im1 == im2) # Test imsave() if os.path.isfile(fname2): os.remove(fname2) assert not os.path.isfile(fname2) imageio.imsave(fname2, im1[:, :, 0]) imageio.imsave(fname2, im1) assert os.path.isfile(fname2) # Test mimread() fname3 = test_images / "newtonscradle.gif" ims = imageio.mimread(fname3) assert isinstance(ims, list) assert len(ims) > 1 assert ims[0].ndim == 3 assert ims[0].shape[2] in (1, 3, 4) # Test protection with raises(RuntimeError): imageio.mimread(test_images / "chelsea.png", "dummy", length=np.inf) if IS_PYPY: return # no support for npz format :( # Test mimsave() fname5 = str(fname3.with_suffix("")) fname5 += "2.npz" if os.path.isfile(fname5): os.remove(fname5) assert not os.path.isfile(fname5) imageio.mimsave(fname5, [im[:, :, 0] for im in ims]) imageio.mimsave(fname5, ims) assert os.path.isfile(fname5) # Test volread() fname4 = test_images / "stent.npz" vol = imageio.volread(fname4) assert vol.ndim == 3 assert vol.shape[0] == 256 assert vol.shape[1] == 128 assert vol.shape[2] == 128 # Test volsave() volc = np.zeros((10, 10, 10, 3), np.uint8) # color volume fname6 = tmp_path / "stent2.npz" if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.volsave(fname6, volc) imageio.volsave(fname6, vol) assert os.path.isfile(fname6) # Test mvolread() vols = imageio.mvolread(fname4) assert isinstance(vols, list) assert len(vols) == 1 assert vols[0].shape == vol.shape # Test mvolsave() if os.path.isfile(fname6): os.remove(fname6) assert not os.path.isfile(fname6) imageio.mvolsave(fname6, [volc, volc]) imageio.mvolsave(fname6, vols) assert os.path.isfile(fname6) # Fail for save functions raises(ValueError, imageio.imsave, fname2, np.zeros((100, 100, 5))) raises(ValueError, imageio.imsave, fname2, 42) raises(ValueError, imageio.mimsave, fname5, [np.zeros((100, 100, 5))]) raises(ValueError, imageio.mimsave, fname5, [42]) raises(ValueError, imageio.volsave, fname6, np.zeros((100, 100, 100, 40))) raises(ValueError, imageio.volsave, fname6, 42) raises(ValueError, imageio.mvolsave, fname6, [np.zeros((90, 90, 90, 40))]) raises(ValueError, imageio.mvolsave, fname6, [42])
def save_tensor_as_color_img(img_tensor, filename): np_array = img_tensor.cpu().detach().numpy() imageio.save(filename, np_array)
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.shape == im2.shape 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.shape == im2.shape assert (im == im2).all() # note: this does not imply that the shape match! assert len(ims) == 3 for i in range(3): assert ims[i].shape == im2.shape assert (ims[i] == im2).all() # Read all planes as one array - we call it a volume for clarity vol = imageio.volread(filename1) vols = imageio.mvolread(filename1) assert vol.shape == (3, ) + im2.shape assert len(vols) == 1 and vol.shape == vols[0].shape for i in range(3): assert (vol[i] == im2).all() # 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': 'SEPARATE'}) # was "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' # not there in later version # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) # Ensure imread + imwrite works round trip filename3 = os.path.join(test_dir, 'test_tiff2.tiff') im1 = imageio.imread(filename1) imageio.imwrite(filename3, im1) 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 assert 'software' in md assert md['software'] == 'testsoftware' assert 'description' in md assert md['description'] == 'test desc'
def test_read_and_write(): 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" frame1, frame2, frame3 = 41, 131, 227 # 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 to reference frames in steps. OUR code will skip steps im11 = R.get_data(frame1) im12 = R.get_data(frame2) im13 = R.get_data(frame3) # Now go backwards, seek will kick in R.get_next_data() im23 = R.get_data(frame3) im22 = R.get_data(frame2) im21 = R.get_data(frame1) # Also use set_image_index R.set_image_index(frame2) im32 = R.get_next_data() R.set_image_index(frame3) im33 = R.get_next_data() R.set_image_index(frame1) im31 = R.get_next_data() for im in (im11, im12, im13, im21, im22, im23, im31, im32, im33): assert im.shape == (720, 1280, 3) assert (im11 == im21).all() and (im11 == im31).all() assert (im12 == im22).all() and (im12 == im32).all() assert (im13 == im23).all() and (im13 == im33).all() assert not (im11 == im12).all() assert not (im11 == im13).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) for im in ims2: assert im.shape == (720, 1280, 3) # 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_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.shape == im2.shape 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.shape == im2.shape assert (im == im2).all() # note: this does not imply that the shape match! assert len(ims) == 3 for i in range(3): assert ims[i].shape == im2.shape assert (ims[i] == im2).all() # Read all planes as one array - we call it a volume for clarity vol = imageio.volread(filename1) vols = imageio.mvolread(filename1) assert vol.shape == (3, ) + im2.shape assert len(vols) == 1 and vol.shape == vols[0].shape for i in range(3): assert (vol[i] == im2).all() # 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': 'SEPARATE'}) # was "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' # not there in later version # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) # Ensure imread + imwrite works round trip filename3 = os.path.join(test_dir, 'test_tiff2.tiff') im1 = imageio.imread(filename1) imageio.imwrite(filename3, im1) 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()
for s in range(SAMPLES): for imgs, view in [(imgs_birds_eye, 'view0'), (imgs_kinect, 'view1'), (imgs_bottom, 'view2')]: first_fr = [imgs[0]] last_fr = [imgs[-1]] samps = sorted(random.sample(range(1, IN_T), k=OUT_T - 2)) img_out = first_fr + [imgs[i] for i in samps] + last_fr gif_out = gif_out_dir + 'cond' + str(cntr) + '.samp' + str( s) + '.' + view + '.gif' print 'Outputing', len(img_out), 'images to', gif_out writer = imageio.save(gif_out, duration=(IN_T / 20.) / OUT_T, quantizer=0, palettesize=256) i = 0 for frame in img_out: writer.append_data(frame) i += 1 print 'Wrote', i, 'frames for', view samps = [0] + samps + [IN_T - 1] # print 'Outputting', len(samps), 'samples' demoX[s, cntr, :, :7] = traj_angles[samps, :] demoX[s, cntr, :, 7:] = traj_eep[samps, :] demoU[s, cntr, :, :7] = traj_vels[samps, :] demoU[s, cntr, :, 7:] = traj_eep_vel[samps, :] cntr += 1
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.shape == im2.shape 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.shape == im2.shape assert (im == im2).all() # note: this does not imply that the shape match! assert len(ims) == 3 for i in range(3): assert ims[i].shape == im2.shape assert (ims[i] == im2).all() # Read all planes as one array - we call it a volume for clarity vol = imageio.volread(filename1) vols = imageio.mvolread(filename1) assert vol.shape == (3, ) + im2.shape assert len(vols) == 1 and vol.shape == vols[0].shape for i in range(3): assert (vol[i] == im2).all() # 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": "SEPARATE"}) # was "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' # not there in later version # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) # Ensure imread + imwrite works round trip filename3 = os.path.join(test_dir, "test_tiff2.tiff") im1 = imageio.imread(filename1) imageio.imwrite(filename3, im1) 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) with imageio.get_writer(filename1, software="testsoftware") as w: w.append_data(np.zeros((10, 10)), meta={ "description": "test desc", "datetime": dt }) w.append_data(np.zeros((10, 10)), meta={"description": "another desc"}) with imageio.get_reader(filename1) as r: for md in r.get_meta_data(), r.get_meta_data(0): assert "datetime" in md assert md["datetime"] == dt assert "software" in md assert md["software"] == "testsoftware" assert "description" in md assert md["description"] == "test desc" md = r.get_meta_data(1) assert "description" in md assert md["description"] == "another desc"