Beispiel #1
0
    def test_psnr(self):
        """
        SCENARIO:  Convert TIFF file to JP2 with the irreversible transform.

        EXPECTED RESULT:  data matches, the irreversible transform is confirmed
        """
        with Tiff2Jp2k(self.minisblack_spp1_path,
                       self.temp_jp2_filename,
                       psnr=(30, 35, 40, 0)) as j:
            j.run()

        j = Jp2k(self.temp_jp2_filename)

        d = {}
        for layer in range(4):
            j.layer = layer
            d[layer] = j[:]

        with warnings.catch_warnings():
            # MSE is zero for that first image, resulting in a divide-by-zero
            # warning
            warnings.simplefilter('ignore')
            psnr = [
                fixtures.skimage.metrics.peak_signal_noise_ratio(
                    fixtures.skimage.data.moon(), d[j]) for j in range(4)
            ]

        # That first image should be lossless.
        self.assertTrue(np.isinf(psnr[0]))

        # None of the subsequent images should have inf PSNR.
        self.assertTrue(not np.any(np.isinf(psnr[1:])))

        # PSNR should increase for the remaining images.
        self.assertTrue(np.all(np.diff(psnr[1:])) > 0)
Beispiel #2
0
    def test_rgb_stripped_bottom_of_tile_coincides_with_bottom_of_strip(self):
        """
        Scenario:  input TIFF is evenly divided into strips, but the tile size
        does not evenly divide either dimension.  The strip size is 32.  The
        tile size is 13x13, so the jp2k tile in tile row 4 and column 0 will
        have it's last row only one pixel past the last row of the tiff tile
        in row 2 and column 0.

        Expected Result:  no errors
        """
        with Tiff2Jp2k(self.goodstuff_path,
                       self.temp_jp2_filename,
                       tilesize=(75, 75)) as j:
            j.run()

        jp2 = Jp2k(self.temp_jp2_filename)
        actual = jp2[:]

        np.testing.assert_array_equal(actual, self.goodstuff_data)

        c = jp2.get_codestream()
        self.assertEqual(c.segment[1].xsiz, 480)
        self.assertEqual(c.segment[1].ysiz, 800)
        self.assertEqual(c.segment[1].xtsiz, 75)
        self.assertEqual(c.segment[1].ytsiz, 75)
Beispiel #3
0
    def setup_rgb_evenly_stripped(cls, path):
        """
        SCENARIO:  create a simple RGB stripped image, stripsize of 32
        """
        j = Jp2k(glymur.data.goodstuff())
        data = j[:]
        h, w, spp = data.shape
        rps = 32

        fp = libtiff.open(path, mode='w')

        libtiff.setField(fp, 'Photometric', libtiff.Photometric.RGB)
        libtiff.setField(fp, 'Compression', libtiff.Compression.DEFLATE)
        libtiff.setField(fp, 'ImageLength', data.shape[0])
        libtiff.setField(fp, 'ImageWidth', data.shape[1])
        libtiff.setField(fp, 'RowsPerStrip', rps)
        libtiff.setField(fp, 'BitsPerSample', 8)
        libtiff.setField(fp, 'SamplesPerPixel', spp)
        libtiff.setField(fp, 'PlanarConfig', libtiff.PlanarConfig.CONTIG)

        for stripnum in range(25):
            row = rps * stripnum
            stripdata = data[row:row + rps, :, :].copy()
            libtiff.writeEncodedStrip(fp, stripnum, stripdata)

        libtiff.close(fp)

        cls.goodstuff_data = data
        cls.goodstuff_path = path
Beispiel #4
0
 def test_crg_segment(self):
     """
     Verify parsing of the CRG segment
     """
     j2k = Jp2k(self.p0_03)
     c = j2k.get_codestream()
     self.assertEqual(c.segment[6].xcrg, (65424, ))
     self.assertEqual(c.segment[6].ycrg, (32558, ))
Beispiel #5
0
 def test_ppt_segment(self):
     """
     Verify parsing of the PPT segment
     """
     with ir.path(data, 'p1_06.j2k') as path:
         j2k = Jp2k(path)
     c = j2k.get_codestream(header_only=False)
     self.assertEqual(c.segment[6].zppt, 0)
Beispiel #6
0
 def test_missing_colr_box(self):
     """jp2h must have a colr box"""
     j2k = Jp2k(self.j2kfile)
     boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]
     boxes[2].box = [self.ihdr]
     with open(self.temp_jp2_filename, mode='wb') as tfile:
         with self.assertRaises(InvalidJp2kError):
             j2k.wrap(tfile.name, boxes=boxes)
Beispiel #7
0
 def test_plt_segment(self):
     """
     Verify parsing of the PLT segment
     """
     with ir.path(data, 'issue142.j2k') as path:
         c = Jp2k(path).get_codestream(header_only=False)
     self.assertEqual(c.segment[7].zplt, 0)
     self.assertEqual(len(c.segment[7].iplt), 59)
Beispiel #8
0
 def test_bad_approx_jp2_field(self):
     """JP2 has requirements for approx field"""
     j2k = Jp2k(self.j2kfile)
     boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]
     colr = ColourSpecificationBox(colorspace=SRGB, approximation=1)
     boxes[2].box = [self.ihdr, colr]
     with open(self.temp_jp2_filename, mode='wb') as tfile:
         with self.assertRaises(InvalidJp2kError):
             j2k.wrap(tfile.name, boxes=boxes)
Beispiel #9
0
    def test_colr_with_out_enum_cspace(self):
        """must supply an enumerated colorspace when writing"""
        j2k = Jp2k(self.j2kfile)

        boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]
        boxes[2].box = [self.ihdr, ColourSpecificationBox(colorspace=None)]
        with open(self.temp_jp2_filename, mode='wb') as tfile:
            with self.assertRaises(InvalidJp2kError):
                j2k.wrap(tfile.name, boxes=boxes)
Beispiel #10
0
    def test_ppt_segment(self):
        """
        Verify parsing of the PPT segment
        """
        relpath = os.path.join('data', 'p1_06.j2k')
        filename = pkg.resource_filename(__name__, relpath)

        c = Jp2k(filename).get_codestream(header_only=False)
        self.assertEqual(c.segment[6].zppt, 0)
Beispiel #11
0
    def test_cinema2K_bad_frame_rate(self):
        """
        SCENARIO:  The cinema2k frame rate is not either 24 or 48.

        EXPECTED RESULT:  ValueError
        """
        with open(self.temp_j2k_filename, mode='wb') as tfile:
            with self.assertRaises(ValueError):
                Jp2k(tfile.name, data=self.jp2_data, cinema2k=36)
Beispiel #12
0
    def test_siz_segment_ssiz_unsigned(self):
        """ssiz attribute to be removed in future release"""
        j = Jp2k(self.jp2file)
        codestream = j.get_codestream()

        # The ssiz attribute was simply a tuple of raw bytes.
        # The first 7 bits are interpreted as the bitdepth, the MSB determines
        # whether or not it is signed.
        self.assertEqual(codestream.segment[1].ssiz, (7, 7, 7))
Beispiel #13
0
    def test_basic_xml(self):
        """Should be able to write a basic XMLBox"""
        j2k = Jp2k(self.j2kfile)

        self.jp2h.box = [self.ihdr, self.colr]

        doc = ET.parse(BytesIO(b'<?xml version="1.0"?><data>0</data>'))
        xmlb = glymur.jp2box.XMLBox(xml=doc)
        self.assertEqual(ET.tostring(xmlb.xml.getroot()), b'<data>0</data>')

        boxes = [self.jp2b, self.ftyp, self.jp2h, xmlb, self.jp2c]

        with tempfile.NamedTemporaryFile(suffix=".jp2") as tfile:
            j2k.wrap(tfile.name, boxes=boxes)
            jp2 = Jp2k(tfile.name)
            self.assertEqual(jp2.box[3].box_id, 'xml ')
            self.assertEqual(ET.tostring(jp2.box[3].xml.getroot()),
                             b'<data>0</data>')
Beispiel #14
0
 def test_crg_segment(self):
     """
     Verify parsing of the CRG segment
     """
     with ir.path(data, 'p0_03.j2k') as path:
         j2k = Jp2k(path)
     c = j2k.get_codestream()
     self.assertEqual(c.segment[6].xcrg, (65424,))
     self.assertEqual(c.segment[6].ycrg, (32558,))
Beispiel #15
0
 def test_rgn_segment(self):
     """
     Verify parsing of the RGN segment
     """
     j2k = Jp2k(self.p0_06)
     c = j2k.get_codestream()
     self.assertEqual(c.segment[-1].crgn, 0)
     self.assertEqual(c.segment[-1].srgn, 0)
     self.assertEqual(c.segment[-1].sprgn, 11)
Beispiel #16
0
    def test_plt_segment(self):
        """
        Verify parsing of the PLT segment
        """
        relpath = os.path.join('data', 'issue142.j2k')
        filename = pkg.resource_filename(__name__, relpath)

        c = Jp2k(filename).get_codestream(header_only=False)
        self.assertEqual(c.segment[7].zplt, 0)
        self.assertEqual(len(c.segment[7].iplt), 59)
Beispiel #17
0
    def test_invalid_component(self):
        """
        SCENARIO:  Decode an invalid component.

        EXPECTED RESULT:  exception
        """
        j2k = Jp2k(self.j2kfile.name)

        with self.assertRaises(ValueError):
            j2k.decoded_components = 10
    def test_moon(self):
        """
        SCENARIO:  construct a jp2 file by repeating a 2D image in a 3x2 grid.

        EXPECTED RESULT:  the written image matches the 3x2 grid
        """
        jp2_data = fixtures.skimage.data.moon()

        shape = jp2_data.shape[0] * 3, jp2_data.shape[1] * 2
        tilesize = (jp2_data.shape[0], jp2_data.shape[1])

        j = Jp2k(self.temp_jp2_filename, shape=shape, tilesize=tilesize)
        for tw in j.get_tilewriters():
            tw[:] = jp2_data

        new_j = Jp2k(self.temp_jp2_filename)
        actual = new_j[:]
        expected = np.tile(jp2_data, (3, 2))
        np.testing.assert_array_equal(actual, expected)
Beispiel #19
0
    def test_cannot_write_a_subarray(self):
        """
        SCENARIO:  Write area by specifying slicing.  Only ':' is
        currently valid as a single slice argument.

        EXPECTED RESULT:  ValueError
        """
        j = Jp2k(self.temp_j2k_filename, shape=self.j2k_data.shape)
        with self.assertRaises(ValueError):
            j[:25, :45, :] = self.j2k_data[:25, :25, :]
Beispiel #20
0
 def test_rgn_segment(self):
     """
     Verify parsing of the RGN segment
     """
     with ir.path(data, 'p0_06.j2k') as path:
         j2k = Jp2k(path)
     c = j2k.get_codestream()
     self.assertEqual(c.segment[-1].crgn, 0)
     self.assertEqual(c.segment[-1].srgn, 0)
     self.assertEqual(c.segment[-1].sprgn, 11)
Beispiel #21
0
 def test_printing(self):
     jp2 = Jp2k(self.hirise_jp2file_name)
     actual = str(jp2.box[4])
     if fixtures.HAVE_GDAL:
         self.assertEqual(actual, fixtures.geotiff_uuid)
     else:
         # Only verify if PY3K, don't bother with Python2.  OrderedDicts
         # print out differently.
         if sys.hexversion >= 0x03040000:
             self.assertEqual(actual, fixtures.geotiff_uuid_without_gdal)
Beispiel #22
0
    def test_invalid_xml_box(self):
        """Should be able to recover info from xml box with bad xml."""
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            jp2k = Jp2k(self._bad_xml_file)

        self.assertEqual(jp2k.box[3].box_id, 'xml ')
        self.assertEqual(jp2k.box[3].offset, 77)
        self.assertEqual(jp2k.box[3].length, 28)
        self.assertIsNone(jp2k.box[3].xml)
Beispiel #23
0
    def test_recover_from_bad_xml(self):
        """Should be able to recover info from xml box with bad xml."""
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            jp2 = Jp2k(self._bad_xml_file)

        self.assertEqual(jp2.box[3].box_id, 'xml ')
        self.assertEqual(jp2.box[3].offset, 77)
        self.assertEqual(jp2.box[3].length, 64)
        self.assertEqual(ET.tostring(jp2.box[3].xml.getroot()),
                         b'<test>this is a test</test>')
    def test_smoke(self):
        """
        SCENARIO:  construct a j2k file by repeating a 3D image in a 2x2 grid.

        EXPECTED RESULT:  the written image matches the 2x2 grid
        """
        j2k_data = fixtures.skimage.data.astronaut()

        shape = (j2k_data.shape[0] * 2, j2k_data.shape[1] * 2,
                 j2k_data.shape[2])
        tilesize = (j2k_data.shape[0], j2k_data.shape[1])

        j = Jp2k(self.temp_j2k_filename, shape=shape, tilesize=tilesize)
        for tw in j.get_tilewriters():
            tw[:] = j2k_data

        new_j = Jp2k(self.temp_j2k_filename)
        actual = new_j[:]
        expected = np.tile(j2k_data, (2, 2, 1))
        np.testing.assert_array_equal(actual, expected)
Beispiel #25
0
    def test_jp2_with_jpx_box(self):
        """If the brand is jp2, then no jpx boxes are allowed."""
        jp2 = Jp2k(self.jp2file)
        boxes = [jp2.box[idx] for idx in [0, 1, 2, 4]]
        boxes = jp2.box

        boxes.append(glymur.jp2box.AssociationBox())

        with open(self.temp_jpx_filename, mode='wb') as tfile:
            with self.assertRaises(RuntimeError):
                jp2.wrap(tfile.name, boxes=boxes)
Beispiel #26
0
    def test_parsing_bad_fptr_box(self):
        """
        SCENARIO: An ftyp box advertises too many bytes to be read.

        EXPECTED RESULT:  A warning is issued.  In this case we also end up
        erroring out anyway since we don't get a valid FileType box.
        """
        with ir.path(data, 'issue438.jp2') as path:
            with self.assertWarns(UserWarning):
                with self.assertRaises(InvalidJp2kError):
                    Jp2k(path)
Beispiel #27
0
    def test_NR_ENC_X_6_2K_24_FULL_CBR_CIRCLE_000_tif_17_encode(self):
        """
        Original test file was

            input/nonregression/X_6_2K_24_FULL_CBR_CIRCLE_000.tif

        """
        # Need to provide the proper size image
        data = glymur.Jp2k(self.jp2file)[:]
        data = np.concatenate((data, data), axis=0)
        data = np.concatenate((data, data), axis=1).astype(np.uint16)
        data = data[:1080, :2048, :]

        with tempfile.NamedTemporaryFile(suffix='.j2k') as tfile:
            if sys.hexversion < 0x03000000:
                with warnings.catch_warnings(record=True) as w:
                    Jp2k(tfile.name, data=data, cinema2k=24)
                assert issubclass(w[-1].category, UserWarning)
            else:
                with self.assertWarns(UserWarning):
                    Jp2k(tfile.name, data=data, cinema2k=24)
Beispiel #28
0
    def test_same_component_several_times(self):
        """
        SCENARIO:  Decode one component multiple times.

        EXPECTED RESULT:  exception
        """

        j2k = Jp2k(self.j2kfile.name)

        with self.assertRaises(glymur.lib.openjp2.OpenJPEGLibraryError):
            j2k.decoded_components = [0, 0]
            j2k[:]
Beispiel #29
0
    def test_negative_component(self):
        """
        SCENARIO:  Provide a negative component.

        EXPECTED RESULT:  exception
        """

        j2k = Jp2k(self.j2kfile.name)

        with self.assertRaises(glymur.lib.openjp2.OpenJPEGLibraryError):
            j2k.decoded_components = -1
            j2k[:]
Beispiel #30
0
 def test_ppm_segment(self):
     """
     Verify parsing of the PPM segment
     """
     with ir.path(data, 'edf_c2_1178956.jp2') as path:
         with warnings.catch_warnings():
             # Lots of things wrong with this file.
             warnings.simplefilter('ignore')
             jp2 = Jp2k(path)
     c = jp2.get_codestream()
     self.assertEqual(c.segment[2].zppm, 0)
     self.assertEqual(len(c.segment[2].data), 9)