Exemplo n.º 1
0
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)
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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"))
Exemplo n.º 4
0
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"))
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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
Exemplo n.º 9
0
def test_lytro_raw_reading():
    """ Test reading of lytro .raw file
    """
    # Get test images
    need_internet()
    raw_file = get_remote_file(RAW_FILENAME)
    raw_meta_file = get_remote_file(RAW_META_FILENAME)

    # Read image and metadata file
    img = imageio.imread(raw_file, format='lytro-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-raw')
    raises(IndexError, test_reader.get_data, -1)
    raises(IndexError, test_reader.get_data, 3)
Exemplo n.º 10
0
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'))
Exemplo n.º 11
0
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
Exemplo n.º 12
0
def download():
    """ Download the ffmpeg exe to your computer.
    """
    plat = get_platform()
    if not (plat and plat in FNAME_PER_PLATFORM):
        raise RuntimeError("FFMPEG exe isn't available for platform %s" % plat)
    get_remote_file('ffmpeg/' + FNAME_PER_PLATFORM[plat])
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
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)
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
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'))
Exemplo n.º 18
0
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
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
def test_request():
    """ Test request object """
    
    # Check uri-type, this is not a public property, so we test the private
    R = Request('http://example.com', 'ri')
    assert R._uri_type == core.request.URI_HTTP
    R = Request('ftp://example.com', 'ri')
    assert R._uri_type == core.request.URI_FTP
    R = Request('file://~/foo.png', 'wi')
    assert R._uri_type == core.request.URI_FILENAME
    R = Request('<video0>', 'rI')
    assert R._uri_type == core.request.URI_BYTES
    R = Request(imageio.RETURN_BYTES, 'wi')
    assert R._uri_type == core.request.URI_BYTES
    #
    fname = get_remote_file('images/chelsea.png', test_dir)
    R = Request(fname, 'ri')
    assert R._uri_type == core.request.URI_FILENAME
    R = Request('~/filethatdoesnotexist', 'wi')
    assert R._uri_type == core.request.URI_FILENAME  # Too short to be bytes
    R = Request(b'x'*600, 'ri')
    assert R._uri_type == core.request.URI_BYTES
    R = Request(sys.stdin, 'ri')
    assert R._uri_type == core.request.URI_FILE
    R = Request(sys.stdout, 'wi')
    assert R._uri_type == core.request.URI_FILE
    # exapand user dir
    R = Request('~/foo', 'wi')
    assert R.filename == os.path.expanduser('~/foo').replace('/', os.path.sep)
    # zip file
    R = Request('~/bar.zip/spam.png', 'wi')
    assert R._uri_type == core.request.URI_ZIPPED
    
    # Test failing inits
    raises(ValueError, Request, '/some/file', None)  # mode must be str
    raises(ValueError, Request, '/some/file', 3)  # mode must be str
    raises(ValueError, Request, '/some/file', '')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'r')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'rii')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'xi')  # mode[0] must be in rw
    raises(ValueError, Request, '/some/file', 'rx')  # mode[1] must be in iIvV?
    #
    raises(IOError, Request, ['invalid', 'uri'] * 10, 'ri')  # invalid uri
    raises(IOError, Request, 4, 'ri')  # invalid uri
    raises(IOError, Request, '/does/not/exist', 'ri')  # reading nonexistent
    raises(IOError, Request, '/does/not/exist.zip/spam.png', 'ri')  # dito
    raises(IOError, Request, 'http://example.com', 'wi')  # no writing here
    raises(IOError, Request, '/does/not/exist.png', 'wi')  # write dir nonexist
    
    # Test auto-download
    R = Request('chelsea.png', 'ri')
    assert R.filename == get_remote_file('images/chelsea.png')
    #
    R = Request('chelsea.zip/chelsea.png', 'ri')
    assert R._filename_zip[0] == get_remote_file('images/chelsea.zip')
    assert R.filename == get_remote_file('images/chelsea.zip') + '/chelsea.png'
Exemplo n.º 21
0
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")
Exemplo n.º 22
0
def test_request():
    """ Test request object """

    # Check uri-type, this is not a public property, so we test the private
    R = Request('http://example.com', 'ri')
    assert R._uri_type == core.request.URI_HTTP
    R = Request('ftp://example.com', 'ri')
    assert R._uri_type == core.request.URI_FTP
    R = Request('file://~/foo.png', 'wi')
    assert R._uri_type == core.request.URI_FILENAME
    R = Request('<video0>', 'rI')
    assert R._uri_type == core.request.URI_BYTES
    R = Request(imageio.RETURN_BYTES, 'wi')
    assert R._uri_type == core.request.URI_BYTES
    #
    fname = get_remote_file('images/chelsea.png', test_dir)
    R = Request(fname, 'ri')
    assert R._uri_type == core.request.URI_FILENAME
    R = Request('~/filethatdoesnotexist', 'wi')
    assert R._uri_type == core.request.URI_FILENAME  # Too short to be bytes
    R = Request(b'x' * 600, 'ri')
    assert R._uri_type == core.request.URI_BYTES
    R = Request(sys.stdin, 'ri')
    assert R._uri_type == core.request.URI_FILE
    R = Request(sys.stdout, 'wi')
    assert R._uri_type == core.request.URI_FILE
    # exapand user dir
    R = Request('~/foo', 'wi')
    assert R.filename == os.path.expanduser('~/foo').replace('/', os.path.sep)
    # zip file
    R = Request('~/bar.zip/spam.png', 'wi')
    assert R._uri_type == core.request.URI_ZIPPED

    # Test failing inits
    raises(ValueError, Request, '/some/file', None)  # mode must be str
    raises(ValueError, Request, '/some/file', 3)  # mode must be str
    raises(ValueError, Request, '/some/file', '')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'r')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'rii')  # mode must be len 2
    raises(ValueError, Request, '/some/file', 'xi')  # mode[0] must be in rw
    raises(ValueError, Request, '/some/file', 'rx')  # mode[1] must be in iIvV?
    #
    raises(IOError, Request, ['invalid', 'uri'] * 10, 'ri')  # invalid uri
    raises(IOError, Request, 4, 'ri')  # invalid uri
    raises(IOError, Request, '/does/not/exist', 'ri')  # reading nonexistent
    raises(IOError, Request, '/does/not/exist.zip/spam.png', 'ri')  # dito
    raises(IOError, Request, 'http://example.com', 'wi')  # no writing here
    raises(IOError, Request, '/does/not/exist.png', 'wi')  # write dir nonexist

    # Test auto-download
    R = Request('imageio:chelsea.png', 'ri')
    assert R.filename == get_remote_file('images/chelsea.png')
    #
    R = Request('imageio:chelsea.zip/chelsea.png', 'ri')
    assert R._filename_zip[0] == get_remote_file('images/chelsea.zip')
    assert R.filename == get_remote_file('images/chelsea.zip') + '/chelsea.png'
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
def test_fetching():
    """ Test fetching of files """
    
    # Clear image files
    if os.path.isdir(test_dir):
        shutil.rmtree(test_dir)   
    
    # This should download the file
    fname1 = get_remote_file('images/chelsea.png', test_dir)
    mtime1 = os.path.getmtime(fname1)
    # This should reuse it
    fname2 = get_remote_file('images/chelsea.png', test_dir)
    mtime2 = os.path.getmtime(fname2)
    # This should overwrite
    fname3 = get_remote_file('images/chelsea.png', test_dir, True)
    mtime3 = os.path.getmtime(fname3)
    # This should too (update this if imageio is still around in 1000 years)
    fname4 = get_remote_file('images/chelsea.png', test_dir, '3014-01-01')
    mtime4 = os.path.getmtime(fname4)
    # This should not
    fname5 = get_remote_file('images/chelsea.png', test_dir, '2014-01-01')
    mtime5 = os.path.getmtime(fname4)
    # 
    assert os.path.isfile(fname1)
    assert fname1 == fname2
    assert fname1 == fname3
    assert fname1 == fname4
    assert fname1 == fname5
    if not sys.platform.startswith('darwin'):
        # weird, but these often fail on my osx VM
        assert mtime1 == mtime2
        assert mtime1 < mtime3
        assert mtime3 < mtime4  
        assert mtime4 == mtime5
    
    # Test failures
    _urlopen = core.fetching.urlopen
    _chunk_read = core.fetching._chunk_read
    #
    raises(IOError, get_remote_file, 'this_does_not_exist', test_dir)
    #
    try:
        core.fetching.urlopen = None
        raises(IOError, get_remote_file, 'images/chelsea.png', None, True)
    finally:
        core.fetching.urlopen = _urlopen
    #
    try:
        core.fetching._chunk_read = None
        raises(IOError, get_remote_file, 'images/chelsea.png', None, True)
    finally:
        core.fetching._chunk_read = _chunk_read
    
    # Coverage miss
    assert '0 bytes' == core.fetching._sizeof_fmt(0)
Exemplo n.º 26
0
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')
Exemplo n.º 27
0
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)
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
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
Exemplo n.º 30
0
def test_select():
    
    fname1 = get_remote_file('images/cockatoo.mp4', test_dir)
    
    F = imageio.formats['avbin']
    assert F.name == 'AVBIN'
    
    assert F.can_read(core.Request(fname1, 'rI'))
    assert not F.can_save(core.Request(fname1, 'wI'))
    assert not F.can_read(core.Request(fname1, 'ri'))
    assert not F.can_read(core.Request(fname1, 'rv'))
    
    R = imageio.read(get_remote_file('images/cockatoo.mp4'), 'avbin')
    assert R.format is F
Exemplo n.º 31
0
def test_select():

    fname1 = get_remote_file('images/cockatoo.mp4', test_dir)

    F = imageio.formats['avbin']
    assert F.name == 'AVBIN'

    assert F.can_read(core.Request(fname1, 'rI'))
    assert not F.can_save(core.Request(fname1, 'wI'))
    assert not F.can_read(core.Request(fname1, 'ri'))
    assert not F.can_read(core.Request(fname1, 'rv'))

    R = imageio.read(get_remote_file('images/cockatoo.mp4'), 'avbin')
    assert R.format is F
Exemplo n.º 32
0
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")
Exemplo n.º 33
0
def test_format_selection():

    formats = imageio.formats
    fname1 = get_remote_file("images/chelsea.png", test_dir)
    fname2 = os.path.join(test_dir, "test.selectext1")
    fname3 = os.path.join(test_dir, "test.haha")
    open(fname2, "wb")
    open(fname3, "wb")

    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname1, "ri"))
    assert F is formats["PNG"]
    F = formats.search_write_format(Request(fname1, "wi"))
    assert F is formats["PNG"]

    # Now with custom format
    format = MyFormat("test_selection", "xx", "selectext1", "i")
    formats.add_format(format)

    # Select this format for files it said it could handle in extensions
    assert ".selectext1" in fname2
    F = formats.search_read_format(Request(fname2, "ri"))
    assert F is format
    F = formats.search_write_format(Request(fname2, "ri"))
    assert F is format

    # But this custom format also can deal with .haha files
    assert ".haha" in fname3
    F = formats.search_read_format(Request(fname3, "ri"))
    assert F is format
    F = formats.search_write_format(Request(fname3, "ri"))
    assert F is format
Exemplo n.º 34
0
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")
Exemplo n.º 35
0
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()
Exemplo n.º 36
0
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()
Exemplo n.º 37
0
def test_format_selection():
    
    formats = imageio.formats
    fname1 = get_remote_file('images/chelsea.png', test_dir)
    fname2 = os.path.join(test_dir, 'test.selectext1')
    fname3 = os.path.join(test_dir, 'test.haha')
    open(fname2, 'wb')
    open(fname3, 'wb')
    
    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname1, 'ri'))
    assert F is formats['PNG']
    F = formats.search_write_format(Request(fname1, 'wi'))
    assert F is formats['PNG']
    
    # Now with custom format
    format = MyFormat('test_selection', 'xx', 'selectext1', 'i')
    formats.add_format(format)
    
    # Select this format for files it said it could handle in extensions
    assert '.selectext1' in fname2
    F = formats.search_read_format(Request(fname2, 'ri'))
    assert F is format
    F = formats.search_write_format(Request(fname2, 'ri'))
    assert F is format
    
    # But this custom format also can deal with .haha files
    assert '.haha' in fname3
    F = formats.search_read_format(Request(fname3, 'ri'))
    assert F is format
    F = formats.search_write_format(Request(fname3, 'ri'))
    assert F is format
Exemplo n.º 38
0
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'
Exemplo n.º 39
0
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)
Exemplo n.º 40
0
def get_freeimage_lib():
    """ Ensure we have our version of the binary freeimage lib.
    """ 
    # Get platform
    if sys.platform.startswith('linux'):
        plat = 'linux%i' % (struct.calcsize('P') * 8)
    elif sys.platform.startswith('win'):
        plat = 'win%i' % (struct.calcsize('P') * 8)
    elif sys.platform.startswith('darwin'):
        plat = 'osx64'
    else:  # pragma: no cover
        plat = None
    
    LIBRARIES = {
        'osx64': 'libfreeimage-3.16.0-osx10.6.dylib',
        'win32': 'FreeImage-3.15.4-win32.dll',  # Also works on Python 3.3
        'win64': 'FreeImage-3.15.1-win64.dll',
        'linux32': 'libfreeimage-3.16.0-linux32.so',
        'linux64': 'libfreeimage-3.16.0-linux64.so',
    }
    
    # Get filename to load
    if plat:
        try:
            return get_remote_file('freeimage/' + LIBRARIES[plat])
        except RuntimeError as e:  # pragma: no cover
            print(str(e))
Exemplo n.º 41
0
def test_jpg():

    for float in (False, True):
        for crop in (0, 1, 2):
            for colors in (0, 1, 3):
                fname = fnamebase + '%i.%i.%i.jpg' % (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, 1.1)  # lossy

    # No alpha in JPEG
    raises(Exception, imageio.imsave, fname, im4)

    # Parameters
    imageio.imsave(fnamebase + '.jpg',
                   im3,
                   progressive=True,
                   optimize=True,
                   baseline=True)

    # Parameter fail
    raises(TypeError, imageio.imread, fnamebase + '.jpg', notavalidkwarg=True)
    raises(TypeError, imageio.imsave, fnamebase + '.jpg', im, notavalidk=True)

    # Compression
    imageio.imsave(fnamebase + '1.jpg', im3, quality=10)
    imageio.imsave(fnamebase + '2.jpg', im3, quality=90)
    s1 = os.stat(fnamebase + '1.jpg').st_size
    s2 = os.stat(fnamebase + '2.jpg').st_size
    assert s2 > s1
    raises(ValueError, imageio.imsave, fnamebase + '.jpg', im, quality=120)

    # 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
Exemplo n.º 42
0
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
Exemplo n.º 43
0
def test_format_selection():

    formats = imageio.formats
    fname1 = get_remote_file('images/chelsea.png', test_dir)
    fname2 = os.path.join(test_dir, 'test.selectext1')
    fname3 = os.path.join(test_dir, 'test.haha')
    open(fname2, 'wb')
    open(fname3, 'wb')

    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname1, 'ri'))
    assert F is formats['PNG']
    F = formats.search_write_format(Request(fname1, 'wi'))
    assert F is formats['PNG']

    # Now with custom format
    format = MyFormat('test_selection', 'xx', 'selectext1', 'i')
    formats.add_format(format)

    # Select this format for files it said it could handle in extensions
    assert '.selectext1' in fname2
    F = formats.search_read_format(Request(fname2, 'ri'))
    assert F is format
    F = formats.search_write_format(Request(fname2, 'ri'))
    assert F is format

    # But this custom format also can deal with .haha files
    assert '.haha' in fname3
    F = formats.search_read_format(Request(fname3, 'ri'))
    assert F is format
    F = formats.search_write_format(Request(fname3, 'ri'))
    assert F is format
Exemplo n.º 44
0
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
Exemplo n.º 45
0
def test_format_selection():

    formats = imageio.formats
    fname1 = get_remote_file("images/chelsea.png", test_dir)
    fname2 = os.path.join(test_dir, "test.selectext1")
    fname3 = os.path.join(test_dir, "test.haha")
    open(fname2, "wb")
    open(fname3, "wb")

    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname1, "ri"))
    assert F is formats["PNG"]
    F = formats.search_write_format(Request(fname1, "wi"))
    assert F is formats["PNG"]

    # Now with custom format
    format = MyFormat("test_selection", "xx", "selectext1", "i")
    formats.add_format(format)

    # Select this format for files it said it could handle in extensions
    assert ".selectext1" in fname2
    F = formats.search_read_format(Request(fname2, "ri"))
    assert F is format
    F = formats.search_write_format(Request(fname2, "ri"))
    assert F is format

    # But this custom format also can deal with .haha files
    assert ".haha" in fname3
    F = formats.search_read_format(Request(fname3, "ri"))
    assert F is format
    F = formats.search_write_format(Request(fname3, "ri"))
    assert F is format
Exemplo n.º 46
0
def get_exe():
    """ Get ffmpeg exe
    """
    # Is the ffmpeg exe overridden?
    exe = os.getenv('IMAGEIO_FFMPEG_EXE', None)
    if exe:  # pragma: no cover
        return exe

    # Check if ffmpeg is in PATH
    try:
        with open(os.devnull, "w") as null:
            sp.check_call(["ffmpeg", "-version"],
                          stdout=null,
                          stderr=sp.STDOUT)
            return "ffmpeg"
    # ValueError is raised on failure on OS X through Python 2.7.11
    # https://bugs.python.org/issue26083
    except (OSError, ValueError, sp.CalledProcessError):
        pass

    plat = get_platform()

    # Check if ffmpeg is installed in Python environment
    # (e.g. via conda install ffmpeg -c conda-forge)
    exe = None
    if plat.startswith('win'):
        exe = os.path.join(sys.prefix, 'Library', 'bin', 'ffmpeg.exe')
    else:
        exe = os.path.join(sys.prefix, 'bin', 'ffmpeg')
    # Does the found Python-ffmpeg work?
    if exe and os.path.isfile(exe):
        try:
            with open(os.devnull, "w") as null:
                sp.check_call([exe, "-version"], stdout=null, stderr=sp.STDOUT)
                return exe
        except (OSError, ValueError, sp.CalledProcessError):
            pass

    # Finally, try and use the executable that we provide
    if plat and plat in FNAME_PER_PLATFORM:
        try:
            exe = get_remote_file('ffmpeg/' + FNAME_PER_PLATFORM[plat],
                                  auto=False)
            os.chmod(exe, os.stat(exe).st_mode | stat.S_IEXEC)  # executable
            return exe
        except NeedDownloadError:
            raise NeedDownloadError('Need ffmpeg exe. '
                                    'You can obtain it with either:\n'
                                    '  - install using conda: '
                                    'conda install ffmpeg -c conda-forge\n'
                                    '  - download by calling: '
                                    'imageio.plugins.ffmpeg.download()')
        except InternetNotAllowedError:
            pass  # explicitly disallowed by user
        except OSError as err:  # pragma: no cover
            logging.warning("Warning: could not find imageio's "
                            "ffmpeg executable:\n%s" % str(err))

    # Fallback, let's hope the system has ffmpeg
    return 'ffmpeg'
Exemplo n.º 47
0
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
Exemplo n.º 48
0
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())
Exemplo n.º 49
0
def test_format_manager():
    """ Test working of the format manager """
    
    formats = imageio.formats
    
    # Test basics of FormatManager
    assert isinstance(formats, FormatManager)
    assert len(formats) > 0
    assert 'FormatManager' in repr(formats)
    
    # Get docs
    smalldocs = str(formats)
    #fulldocs = formats.create_docs_for_all_formats()
    
    # Check each format ...
    for format in formats:
        #  That each format is indeed a Format
        assert isinstance(format, Format)
        # That they are mentioned
        assert format.name in smalldocs
        #assert format.name in fulldocs
    
    fname = get_remote_file('images/chelsea.png', test_dir)
    fname2 = fname[:-3] + 'noext'
    shutil.copy(fname, fname2)
    
    # Check getting
    F1 = formats['PNG']
    F2 = formats['.png']
    F3 = formats[fname2]  # will look in file itself
    assert F1 is F2
    assert F1 is F3
    # Check getting
    F1 = formats['DICOM']
    F2 = formats['.dcm']
    F3 = formats['dcm']  # If omitting dot, format is smart enough to try with
    assert F1 is F2
    assert F1 is F3
    # Fail
    raises(ValueError, formats.__getitem__, 678)  # must be str
    raises(IndexError, formats.__getitem__, '.nonexistentformat')
    
    # Adding a format
    myformat = Format('test', 'test description', 'testext1 testext2')
    formats.add_format(myformat)
    assert myformat in [f for f in formats]
    assert formats['testext1'] is myformat
    assert formats['testext2'] is myformat
    # Fail
    raises(ValueError, formats.add_format, 678)  # must be Format
    raises(ValueError, formats.add_format, myformat)  # cannot add twice
    
    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname, 'ri'))
    assert F is formats['PNG']
    F = formats.search_save_format(Request(fname, 'wi'))
    assert F is formats['PNG']
Exemplo n.º 50
0
def test_jpg():
    
    for float in (False, True):
        for crop in (0, 1, 2):
            for colors in (0, 1, 3):
                fname = fnamebase + '%i.%i.%i.jpg' % (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, 1.1)  # lossy
    
    # No alpha in JPEG
    raises(Exception, imageio.imsave, fname, im4)
    
    # Parameters
    imageio.imsave(fnamebase + '.jpg', im3, progressive=True, optimize=True, 
                   baseline=True)
    
    # Parameter fail
    raises(TypeError, imageio.imread, fnamebase + '.jpg', notavalidkwarg=True)
    raises(TypeError, imageio.imsave, fnamebase + '.jpg', im, notavalidk=True)
    
    # Compression
    imageio.imsave(fnamebase + '1.jpg', im3, quality=10)
    imageio.imsave(fnamebase + '2.jpg', im3, quality=90)
    s1 = os.stat(fnamebase + '1.jpg').st_size
    s2 = os.stat(fnamebase + '2.jpg').st_size
    assert s2 > s1 
    raises(ValueError, imageio.imsave, fnamebase + '.jpg', im, quality=120)
    
    # 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
Exemplo n.º 51
0
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
Exemplo n.º 52
0
def test_format_manager():
    """ Test working of the format manager """
    
    formats = imageio.formats
    
    # Test basics of FormatManager
    assert isinstance(formats, FormatManager)
    assert len(formats) > 0
    assert 'FormatManager' in repr(formats)
    
    # Get docs
    smalldocs = str(formats)
    #fulldocs = formats.create_docs_for_all_formats()
    
    # Check each format ...
    for format in formats:
        #  That each format is indeed a Format
        assert isinstance(format, Format)
        # That they are mentioned
        assert format.name in smalldocs
        #assert format.name in fulldocs
    
    fname = get_remote_file('images/chelsea.png', test_dir)
    fname2 = fname[:-3] + 'noext'
    shutil.copy(fname, fname2)
    
    # Check getting
    F1 = formats['PNG']
    F2 = formats['.png']
    F3 = formats[fname2]  # will look in file itself
    assert F1 is F2
    assert F1 is F3
    # Check getting
    F1 = formats['DICOM']
    F2 = formats['.dcm']
    F3 = formats['dcm']  # If omitting dot, format is smart enough to try with
    assert F1 is F2
    assert F1 is F3
    # Fail
    raises(ValueError, formats.__getitem__, 678)  # must be str
    raises(IndexError, formats.__getitem__, '.nonexistentformat')
    
    # Adding a format
    myformat = Format('test', 'test description', 'testext1 testext2')
    formats.add_format(myformat)
    assert myformat in [f for f in formats]
    assert formats['testext1'] is myformat
    assert formats['testext2'] is myformat
    # Fail
    raises(ValueError, formats.add_format, 678)  # must be Format
    raises(ValueError, formats.add_format, myformat)  # cannot add twice
    
    # Test searchinhg for read / write format
    F = formats.search_read_format(Request(fname, 'ri'))
    assert F is formats['PNG']
    F = formats.search_save_format(Request(fname, 'wi'))
    assert F is formats['PNG']
Exemplo n.º 53
0
def test_select():

    fname1 = get_remote_file('images/cockatoo.mp4', test_dir)

    F = imageio.formats['ffmpeg']
    assert F.name == 'FFMPEG'

    assert F.can_read(core.Request(fname1, 'rI'))
    assert F.can_save(core.Request(fname1, 'wI'))
    assert not F.can_read(core.Request(fname1, 'ri'))
    assert not F.can_read(core.Request(fname1, 'rv'))

    R = imageio.read(get_remote_file('images/cockatoo.mp4'), 'ffmpeg')
    assert R.format is F

    # ffmpeg is default
    assert imageio.formats['.mp4'] is F
    assert imageio.formats.search_save_format(core.Request(fname1, 'wI')) is F
    assert imageio.formats.search_read_format(core.Request(fname1, 'rI')) is F
Exemplo n.º 54
0
def test_fetching(tmp_path):
    """Test fetching of files"""

    # This should download the file (force download, because local cache)
    fname1 = get_remote_file("images/chelsea.png", tmp_path, True)
    mtime1 = os.path.getmtime(fname1)
    # This should reuse it
    fname2 = get_remote_file("images/chelsea.png", tmp_path)
    mtime2 = os.path.getmtime(fname2)
    # This should overwrite
    fname3 = get_remote_file("images/chelsea.png", tmp_path, True)
    mtime3 = os.path.getmtime(fname3)
    # This should too (update this if imageio is still around in 1000 years)
    fname4 = get_remote_file("images/chelsea.png", tmp_path, "3014-01-01")
    mtime4 = os.path.getmtime(fname4)
    # This should not
    fname5 = get_remote_file("images/chelsea.png", tmp_path, "2014-01-01")
    mtime5 = os.path.getmtime(fname4)
    #
    assert os.path.isfile(fname1)
    assert fname1 == fname2
    assert fname1 == fname3
    assert fname1 == fname4
    assert fname1 == fname5
    if not sys.platform.startswith("darwin"):
        # weird, but these often fail on my osx VM
        assert mtime1 == mtime2
        assert mtime1 < mtime3
        assert mtime3 < mtime4
        assert mtime4 == mtime5

    # Test failures
    _urlopen = core.fetching.urlopen
    _chunk_read = core.fetching._chunk_read
    #
    with pytest.raises(IOError):
        get_remote_file("this_does_not_exist", tmp_path)
    #
    try:
        core.fetching.urlopen = None
        raises(IOError, get_remote_file, "images/chelsea.png", None, True)
    finally:
        core.fetching.urlopen = _urlopen
    #
    try:
        core.fetching._chunk_read = None
        raises(IOError, get_remote_file, "images/chelsea.png", None, True)
    finally:
        core.fetching._chunk_read = _chunk_read
    #
    try:
        os.environ["IMAGEIO_NO_INTERNET"] = "1"
        raises(IOError, get_remote_file, "images/chelsea.png", None, True)
    finally:
        del os.environ["IMAGEIO_NO_INTERNET"]
    # Coverage miss
    assert "0 bytes" == core.fetching._sizeof_fmt(0)
Exemplo n.º 55
0
def test_select():
    
    fname1 = get_remote_file('images/cockatoo.mp4', test_dir)
    
    F = imageio.formats['ffmpeg']
    assert F.can_read(core.Request(fname1, 'rI'))
    assert F.can_save(core.Request(fname1, 'wI'))
    assert not F.can_read(core.Request(fname1, 'ri'))
    assert not F.can_read(core.Request(fname1, 'rv'))

    assert imageio.formats.search_save_format(core.Request(fname1, 'rI')) is F
Exemplo n.º 56
0
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
Exemplo n.º 57
0
def test_select():

    fname1 = get_remote_file("images/cockatoo.mp4", test_dir)

    F = imageio.formats["avbin"]
    assert F.name == "AVBIN"

    assert F.can_read(core.Request(fname1, "rI"))
    assert not F.can_write(core.Request(fname1, "wI"))
    assert not F.can_read(core.Request(fname1, "ri"))
    assert not F.can_read(core.Request(fname1, "rv"))
Exemplo n.º 58
0
def test_fits_format():

    # 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'))
Exemplo n.º 59
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()