def test_lytro_f01_raw_format(): """ Test basic read/write properties of LytroRawFormat """ # Get test images need_internet() lfr_file = get_remote_file(LFR_FILENAME) raw_illum_file = get_remote_file(RAW_ILLUM_FILENAME) lfp_file = get_remote_file(LFP_FILENAME) raw_f01_file = get_remote_file(RAW_F0_FILENAME) png_file = get_remote_file(PNG_FILENAME) # Test lytro raw format format = imageio.formats["lytro-illum-raw"] assert format.name == "LYTRO-ILLUM-RAW" assert format.__module__.endswith("lytro") # Test can read, cannot write assert format.can_read(Request(raw_f01_file, "ri")) # Test cannot read, cannot write assert not format.can_read(Request(raw_f01_file, "rv")) assert not format.can_read(Request(raw_f01_file, "rI")) assert not format.can_read(Request(raw_f01_file, "rV")) assert not format.can_read(Request(lfr_file, "ri")) assert not format.can_read(Request(lfp_file, "ri")) assert not format.can_read(Request(png_file, "ri")) assert not format.can_write(Request(raw_f01_file, "wi")) assert not format.can_write(Request(lfr_file, "wi")) assert not format.can_write(Request(lfp_file, "wi")) assert not format.can_write(Request(raw_illum_file, "wi")) assert not format.can_write(Request(png_file, "wi"))
def test_webcam_process_termination(): """ Test for issue #343. Ensures that an ffmpeg process streaming from webcam is terminated properly when the reader is closed. """ need_internet() def ffmpeg_alive(): """ Enumerate ffmpeg processes, then wait for them to terminate """ ffmpeg_processes = [] for process in psutil.process_iter(): # NOTE: using list comprehension here caused NoSuchProcess # exception in some cases. try: if "ffmpeg" in process.name().lower(): ffmpeg_processes.append(process) except psutil.NoSuchProcess as e: print(e.message) still_alive = False if ffmpeg_processes: __, still_alive = psutil.wait_procs(ffmpeg_processes, timeout=1) return still_alive try: # Open the first webcam found. with imageio.get_reader("<video0>") as reader: assert reader._proc is not None assert reader._proc.poll() is None, "ffmpeg process should be active" assert ffmpeg_alive() # Ensure that the corresponding ffmpeg process has been terminated. assert reader._proc is None assert not ffmpeg_alive() except IndexError: skip("no webcam")
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_lfr_format(): """ Test basic read/write properties of LytroLfrFormat """ # Get test images need_internet() lfr_file = get_remote_file(LFR_FILENAME) raw_file = get_remote_file(RAW_FILENAME) png_file = get_remote_file(PNG_FILENAME) # Test lytro lfr format format = imageio.formats['lytro-lfr'] assert format.name == 'LYTRO-LFR' assert format.__module__.endswith('lytro') # Test can read assert format.can_read(Request(lfr_file, 'ri')) # Test cannot read, cannot write assert not format.can_read(Request(lfr_file, 'rv')) assert not format.can_read(Request(lfr_file, 'rI')) assert not format.can_read(Request(lfr_file, 'rV')) assert not format.can_read(Request(raw_file, 'ri')) assert not format.can_read(Request(png_file, 'ri')) assert not format.can_write(Request(lfr_file, 'wi')) assert not format.can_write(Request(raw_file, 'wi')) assert not format.can_write(Request(png_file, 'wi'))
def test_findlib2(): if not sys.platform.startswith("linux"): skip("test on linux only") need_internet() # need our own version of FI to test this bit # Candidate libs for common freeimage fi_dir = os.path.join(core.appdata_dir("imageio"), "freeimage") if not os.path.isdir(fi_dir): os.mkdir(fi_dir) dirs, paths = core.findlib.generate_candidate_libs(["libfreeimage"], [fi_dir]) # assert fi_dir in dirs -> Cannot test: lib may not exist assert paths open(os.path.join(fi_dir, "notalib.test.so"), "wb") # Loading libs gllib = ctypes.util.find_library("GL") core.load_lib([gllib], []) core.load_lib([], ["libfreeimage"], [fi_dir]) # Fail raises(ValueError, core.load_lib, [], []) # Nothing given raises(ValueError, core.load_lib, ["", None], []) # Nothing given raises(OSError, core.load_lib, ["thislibdoesnotexist_foobar"], []) raises(OSError, core.load_lib, [], ["notalib"], [fi_dir])
def test_types(): need_internet() fname1 = get_remote_file("images/stent.swf", test_dir) fname2 = fname1[:-4] + ".out3.swf" for dtype in [ np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, ]: for shape in [(100, 1), (100, 3)]: # Repeats an identity matrix, just for testing im1 = np.dstack((np.identity(shape[0], dtype=dtype), ) * shape[1]) imageio.mimsave(fname2, [im1], "swf") im2 = imageio.mimread(fname2, "swf")[0] assert im2.shape == (100, 100, 4) assert im2.dtype == np.uint8 if len(shape) == 3 and dtype == np.uint8: assert (im1[:, :, 0] == im2[:, :, 0]).all()
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_findlib2(): if not sys.platform.startswith('linux'): skip('test on linux only') need_internet() # need our own version of FI to test this bit # Candidate libs for common freeimage fi_dir = os.path.join(core.appdata_dir('imageio'), 'freeimage') if not os.path.isdir(fi_dir): os.mkdir(fi_dir) dirs, paths = core.findlib.generate_candidate_libs(['libfreeimage'], [fi_dir]) #assert fi_dir in dirs -> Cannot test: lib may not exist assert paths open(os.path.join(fi_dir, 'notalib.test.so'), 'wb') # Loading libs gllib = ctypes.util.find_library('GL') core.load_lib([gllib], []) core.load_lib([], ['libfreeimage'], [fi_dir]) # Fail raises(ValueError, core.load_lib, [], []) # Nothing given raises(ValueError, core.load_lib, ['', None], []) # Nothing given raises(OSError, core.load_lib, ['thislibdoesnotexist_foobar'], []) raises(OSError, core.load_lib, [], ['notalib'], [fi_dir])
def test_regression_302(): # When using gamma correction, the result should keep the same dtype need_internet() fname = get_remote_file('images/kodim03.png') im = imageio.imread(fname) assert im.shape == (512, 768, 3) and im.dtype == 'uint8'
def _prepare(): """ Create two dirs, one with one dataset and one with two datasets """ need_internet() global _prepared if _prepared and os.path.isfile(_prepared[2]): return _prepared # Prepare sources fname1 = get_remote_file('images/dicom_sample1.zip') fname2 = get_remote_file('images/dicom_sample2.zip') dname1 = os.path.join(test_dir, 'dicom_sample1') dname2 = os.path.join(test_dir, 'dicom_sample2') # Extract zipfiles z = ZipFile(fname1) z.extractall(dname1) z.extractall(dname2) z = ZipFile(fname2) z.extractall(dname2) # Get arbitrary file names fname1 = os.path.join(dname1, os.listdir(dname1)[0]) fname2 = os.path.join(dname2, os.listdir(dname2)[0]) # Cache and return _prepared = dname1, dname2, fname1, fname2 return dname1, dname2, fname1, fname2
def test_lytro_illum_raw_format(): """ Test basic read/write properties of LytroRawFormat """ # Get test images need_internet() lfr_file = get_remote_file(LFR_FILENAME) raw_illum_file = get_remote_file(RAW_ILLUM_FILENAME) lfp_file = get_remote_file(LFP_FILENAME) raw_f01_file = get_remote_file(RAW_F0_FILENAME) png_file = get_remote_file(PNG_FILENAME) # Test lytro raw format format = imageio.formats['lytro-illum-raw'] assert format.name == 'LYTRO-ILLUM-RAW' assert format.__module__.endswith('lytro') # Test can read, cannot write assert format.can_read(Request(raw_illum_file, 'ri')) # Test cannot read, cannot write assert not format.can_read(Request(raw_illum_file, 'rv')) assert not format.can_read(Request(raw_illum_file, 'rI')) assert not format.can_read(Request(raw_illum_file, 'rV')) assert not format.can_read(Request(lfr_file, 'ri')) assert not format.can_read(Request(lfp_file, 'ri')) assert not format.can_read(Request(png_file, 'ri')) assert not format.can_write(Request(raw_illum_file, 'wi')) assert not format.can_write(Request(lfr_file, 'wi')) assert not format.can_write(Request(lfp_file, 'wi')) assert not format.can_write(Request(raw_f01_file, 'wi')) assert not format.can_write(Request(png_file, 'wi'))
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 test_types(): need_internet() fname1 = get_remote_file("images/stent.swf", test_dir) fname2 = fname1[:-4] + ".out3.swf" for dtype in [ np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, ]: for shape in [(100, 1), (100, 3)]: # Repeats an identity matrix, just for testing im1 = np.dstack((np.identity(shape[0], dtype=dtype),) * shape[1]) imageio.mimsave(fname2, [im1], "swf") im2 = imageio.mimread(fname2, "swf")[0] assert im2.shape == (100, 100, 4) assert im2.dtype == np.uint8 if len(shape) == 3 and dtype == np.uint8: assert (im1[:, :, 0] == im2[:, :, 0]).all()
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_bmp(): need_internet() fname = get_remote_file("images/scribble_P_RGB.bmp", test_dir) imageio.imread(fname) imageio.imread(fname, pilmode="RGB") imageio.imread(fname, pilmode="RGBA")
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_jpg_more(): need_internet() # Test broken JPEG fname = fnamebase + "_broken.jpg" open(fname, "wb").write(b"this is not an image") raises(Exception, imageio.imread, fname) # bb = imageio.imsave(imageio.RETURN_BYTES, get_ref_im(3, 0, 0), "JPEG") with open(fname, "wb") as f: f.write(bb[:400]) f.write(b" ") f.write(bb[400:]) raises(Exception, imageio.imread, fname) # Test EXIF stuff fname = get_remote_file("images/rommel.jpg") im = imageio.imread(fname) assert im.shape[0] > im.shape[1] im = imageio.imread(fname, exifrotate=False) assert im.shape[0] < im.shape[1] im = imageio.imread(fname, exifrotate=2) # Rotation in Python assert im.shape[0] > im.shape[1] # Write the jpg and check that exif data is maintained if sys.platform.startswith("darwin"): return # segfaults on my osx VM, why? imageio.imsave(fnamebase + "rommel.jpg", im) im = imageio.imread(fname) assert im.meta.EXIF_MAIN
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_get_fi_lib(): need_internet() from imageio.plugins._freeimage import get_freeimage_lib lib = get_freeimage_lib() assert os.path.isfile(lib)
def test_webcam(): need_internet() try: imageio.read("<video0>") except Exception: skip("no web cam")
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_webcam(): need_internet() try: imageio.read('<video0>') except Exception: skip('no web cam')
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_png_remote(): # issue #202 need_internet() im = imageio.imread( "https://raw.githubusercontent.com/imageio/" + "imageio-binaries/master/images/astronaut.png" ) assert im.shape == (512, 512, 3)
def test_read_from_url(): need_internet() burl = 'https://raw.githubusercontent.com/imageio/imageio-binaries/master/' url = burl + 'images/stent.swf' ims = imageio.mimread(url) assert len(ims) == 10
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_inside_zipfile(): need_internet() fname = os.path.join(test_dir, "pillowtest.zip") with ZipFile(fname, "w") as z: z.writestr("x.png", open(get_remote_file("images/chelsea.png"), "rb").read()) z.writestr("x.jpg", open(get_remote_file("images/rommel.jpg"), "rb").read()) for name in ("x.png", "x.jpg"): imageio.imread(fname + "/" + name)
def setup_module(): # During this test, pretend that FI is the default format imageio.formats.sort("-FI") # This tests requires our version of the FI lib try: imageio.plugins.freeimage.download() except core.InternetNotAllowedError: # We cannot download; skip all freeimage tests need_internet()
def setup_module(): # During this test, pretend that FI is the default format imageio.formats.sort('-FI') # This tests requires our version of the FI lib try: imageio.plugins.freeimage.download() except imageio.core.InternetNotAllowedError: # We cannot download; skip all freeimage tests need_internet()
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_images_with_transparency(): # Not alpha channel, but transparent pixels, see issue #245 and #246 need_internet() fname = get_remote_file("images/imageio_issue245.gif") im = imageio.imread(fname) assert im.shape == (24, 30, 4) fname = get_remote_file("images/imageio_issue246.png") im = imageio.imread(fname) assert im.shape == (24, 30, 4)
def test_read_format(): need_internet() # 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 test_writer_ffmpeg_params(tmpdir): need_internet() # Test optional ffmpeg_params with a valid option tmpf = tmpdir.join('test.mp4') W = imageio.get_writer(str(tmpf), ffmpeg_params=['-vf', 'scale=320:240']) for i in range(10): W.append_data(np.zeros((100, 100, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) # Check that the optional argument scaling worked. assert "320x240" in W._stderr_catcher.header
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_writer_pixelformat_size_verbose(tmpdir): # Check that video pixel format and size get written as expected. need_internet() # Make sure verbose option works and that default pixelformat is yuv420p tmpf = tmpdir.join('test.mp4', fps=30) W = imageio.get_writer(str(tmpf), ffmpeg_log_level='debug') nframes = 4 # Number of frames in video for i in range(nframes): # Use size divisible by 16 or it gets changed. W.append_data(np.zeros((64, 64, 3), np.uint8)) W.close() # Check that video is correct size & default output video pixel format # is correct W = imageio.get_reader(str(tmpf)) assert len(W) == nframes assert "64x64" in W._stderr_catcher.header assert "yuv420p" in W._stderr_catcher.header # Now check that macroblock size gets turned off if requested W = imageio.get_writer(str(tmpf), macro_block_size=None, ffmpeg_log_level='debug') for i in range(nframes): W.append_data(np.zeros((100, 106, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) assert len(W) == nframes assert "106x100" in W._stderr_catcher.header assert "yuv420p" in W._stderr_catcher.header # Now double check values different than default work W = imageio.get_writer(str(tmpf), macro_block_size=4, ffmpeg_log_level='debug') for i in range(nframes): W.append_data(np.zeros((64, 65, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) assert len(W) == nframes assert "68x64" in W._stderr_catcher.header assert "yuv420p" in W._stderr_catcher.header # Now check that the macroblock works as expected for the default of 16 W = imageio.get_writer(str(tmpf), ffmpeg_log_level='debug') for i in range(nframes): W.append_data(np.zeros((111, 140, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) assert len(W) == nframes # Check for warning message with macroblock assert "144x112" in W._stderr_catcher.header assert "yuv420p" in W._stderr_catcher.header
def test_writer_wmv(tmpdir): need_internet() # WMV has different default codec, make sure it works. tmpf = tmpdir.join('test.wmv') W = imageio.get_writer(str(tmpf), ffmpeg_params=['-v', 'info']) for i in range(10): W.append_data(np.zeros((100, 100, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) # Check that default encoder is msmpeg4 for wmv assert "msmpeg4" in W._stderr_catcher.header
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_fits_format(): need_internet() # We keep the fits files in the imageio-binary repo # Test selection for name in ["fits", ".fits"]: format = imageio.formats["fits"] assert format.name == "FITS" assert format.__module__.endswith(".fits") # Test cannot read png = get_remote_file("images/chelsea.png") assert not format.can_read(Request(png, "ri")) assert not format.can_write(Request(png, "wi"))
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_fits_format(): need_internet() # We keep the fits files in the imageio-binary repo # Test selection for name in ['fits', '.fits']: format = imageio.formats['fits'] assert format.name == 'FITS' assert format.__module__.endswith('.fits') # Test cannot read png = get_remote_file('images/chelsea.png') assert not format.can_read(Request(png, 'ri')) assert not format.can_write(Request(png, 'wi'))
def test_writer_ffmpeg_params(tmpdir): need_internet() # Test optional ffmpeg_params with a valid option # Also putting in an image size that is not divisible by macroblock size # To check that the -vf scale overwrites what it does. tmpf = tmpdir.join('test.mp4') W = imageio.get_writer(str(tmpf), ffmpeg_params=['-vf', 'scale=320:240']) for i in range(10): W.append_data(np.zeros((100, 100, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) # Check that the optional argument scaling worked. assert "320x240" in W._stderr_catcher.header
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_writer_file_properly_closed(tmpdir): # Test to catch if file is correctly closed. # Otherwise it won't play in most players. This seems to occur on windows. need_internet() tmpf = tmpdir.join('test.mp4') W = imageio.get_writer(str(tmpf)) for i in range(10): W.append_data(np.zeros((100, 100, 3), np.uint8)) W.close() W = imageio.get_reader(str(tmpf)) # If Duration: N/A reported by ffmpeg, then the file was not # correctly closed. # This will cause the file to not be readable in many players. assert "Duration: N/A" not in W._stderr_catcher.header