Example #1
0
 def test_info_callback_on_write(self):
     """Verify messages printed when writing an image in verbose mode."""
     j = glymur.Jp2k(self.jp2file)
     tiledata = j[:]
     with tempfile.NamedTemporaryFile(suffix='.jp2') as tfile:
         with patch('sys.stdout', new=StringIO()) as fake_out:
             glymur.Jp2k(tfile.name, data=tiledata, verbose=True)
             actual = fake_out.getvalue().strip()
     expected = '[INFO] tile number 1 / 1'
     self.assertEqual(actual, expected)
Example #2
0
 def test_info_callback_on_write_backwards_compatibility(self):
     """Verify messages printed when writing an image in verbose mode."""
     j = glymur.Jp2k(self.jp2file)
     with warnings.catch_warnings():
         # Ignore a library warning.
         warnings.simplefilter('ignore')
         tiledata = j.read(tile=0)
     with tempfile.NamedTemporaryFile(suffix='.jp2') as tfile:
         with patch('sys.stdout', new=StringIO()) as fake_out:
             glymur.Jp2k(tfile.name, data=tiledata, verbose=True)
         actual = fake_out.getvalue().strip()
     expected = '[INFO] tile number 1 / 1'
     self.assertEqual(actual, expected)
Example #3
0
    def test_info_callback_on_write(self):
        """
        SCENARIO:  write to a JP2 file while in verbose mode

        EXPECTED RESULT:  verify messages from the library
        """
        j = glymur.Jp2k(self.jp2file)
        tiledata = j[:]

        with patch('sys.stdout', new=StringIO()) as fake_out:
            glymur.Jp2k(self.temp_jp2_filename, data=tiledata, verbose=True)
            actual = fake_out.getvalue().strip()

        expected = '[INFO] tile number 1 / 1'
        self.assertEqual(actual, expected)
Example #4
0
    def _loadGlymurImage(self, filename, infile):
        """
        Hack to use Glymur with Python file object

        This code was tested with all release 0.8.x
        """
        # image = glymur.Jp2k(filename)
        # inject a shape  to avoid calling the read function
        if not glymur.__version__.startswith("0.8."):
            raise IOError("Glymur version %s is not supported" % glymur.__version__)

        image = glymur.Jp2k(filename=filename, shape=(1, 1))

        # Move to the end of the file to know the size
        infile.seek(0, 2)
        length = infile.tell()
        infile.seek(0)

        # initialize what it should already be done
        image.length = length
        image._shape = None
        # It is not the only one format supported by Glymur
        # but it is a simplification
        image._codec_format = glymur.lib.openjp2.CODEC_JP2

        # parse the data
        image.box = image.parse_superbox(infile)
        try:
            image._validate()
        except Exception:
            logger.debug("Backtrace", exc_info=True)
            raise IOError("File %s is not a valid format" % filename)

        # Now the image can be used normaly
        return image
Example #5
0
def readimg(fhead,band,pr = False):
    filenames = []
    for i in band:
        if i ==8:
            e = fhead+'B0'+'%s'%i +'.jp2'
            filenames.append(e)
            e1 = fhead+'B'+'%sA'%i +'.jp2'
            filenames.append(e1)
        elif i<10:
            e = fhead+'B0'+'%s'%i +'.jp2'
            filenames.append(e)
        else:
            filename = fhead+'B'+'%s'%i +'.jp2'
            filenames.append(filename)
    #print filenames

    imgdata = {k.split('.')[0][-3:]: [] for k in filenames}

    for i in filenames:
        jp2file = glymur.data.nemo()
        #os.chdir('data')
        jp2 = glymur.Jp2k(i)
        fullres = jp2[:]
        if pr:
            print jp2,'\n',fullres.shape
        
        imgdata[i.split('.')[0][-3:]] = fullres/10000. 
    
    return imgdata
Example #6
0
    def test_bad_tiff_header_byte_order_indication(self):
        """
        SCENARIO:  An invalid TIFF header byte order marker is encountered
        in an Exif UUID box.  Only b'II' and b'MM' are allowed.

        EXPECTED RESULT:  A warning is issued.
        """
        with open(self.temp_jp2_filename, mode='wb') as tfile:

            with open(self.jp2file, 'rb') as ifptr:
                tfile.write(ifptr.read())

            # Write L, T, UUID identifier.
            tfile.write(struct.pack('>I4s', 52, b'uuid'))
            tfile.write(b'JpgTiffExif->JP2')

            tfile.write(b'Exif\x00\x00')

            # Here's the bad byte order.
            tfile.write(b'JI')

            # Write the rest of the header.
            xbuffer = struct.pack('<HI', 42, 8)
            tfile.write(xbuffer)

            # We will write just a single tag.
            tfile.write(struct.pack('<H', 1))

            # 271 is the Make.
            tfile.write(struct.pack('<HHI4s', 271, 2, 3, b'HTC\x00'))
            tfile.flush()

            with self.assertWarns(UserWarning):
                glymur.Jp2k(tfile.name)
Example #7
0
    def test_unrecognized_exif_tag(self):
        """
        SCENARIO:  An Exif UUID box has an unrecognized tag.

        EXPECTED RESULT:  A warning is issued.
        """
        with open(self.temp_jp2_filename, mode='wb') as tfile:

            with open(self.jp2file, 'rb') as ifptr:
                tfile.write(ifptr.read())

            # Write L, T, UUID identifier.
            tfile.write(struct.pack('>I4s', 52, b'uuid'))
            tfile.write(b'JpgTiffExif->JP2')

            tfile.write(b'Exif\x00\x00')
            xbuffer = struct.pack('<BBHI', 73, 73, 42, 8)
            tfile.write(xbuffer)

            # We will write just a single tag.
            tfile.write(struct.pack('<H', 1))

            # The "Make" tag is tag no. 271.  Corrupt it to 171.
            tfile.write(struct.pack('<HHI4s', 171, 2, 3, b'HTC\x00'))
            tfile.flush()

            with self.assertWarns(UserWarning):
                glymur.Jp2k(tfile.name)
Example #8
0
 def getTile(self, x, y, z, pilImageAllowed=False, numpyAllowed=False, **kwargs):
     self._xyzInRange(x, y, z)
     step = int(2 ** (self.levels - 1 - z))
     x0 = x * step * self.tileWidth
     x1 = min((x + 1) * step * self.tileWidth, self.sizeX)
     y0 = y * step * self.tileHeight
     y1 = min((y + 1) * step * self.tileHeight, self.sizeY)
     scale = None
     if z < self._minlevel:
         scale = int(2 ** (self._minlevel - z))
         step = int(2 ** (self.levels - 1 - self._minlevel))
     # possible open the file multiple times so multiple threads can access
     # it concurrently.
     while True:
         try:
             # A timeout prevents uniterupptable waits on some platforms
             openjpegHandle = self._openjpegHandles.get(timeout=1.0)
             break
         except queue.Empty:
             continue
     if openjpegHandle is None:
         openjpegHandle = glymur.Jp2k(self._largeImagePath)
     try:
         tile = openjpegHandle[y0:y1:step, x0:x1:step]
     finally:
         self._openjpegHandles.put(openjpegHandle)
     if scale:
         tile = tile[::scale, ::scale]
     return self._outputTile(tile, TILE_FORMAT_NUMPY, x, y, z,
                             pilImageAllowed, numpyAllowed, **kwargs)
Example #9
0
    def test_bad_tag_datatype(self):
        """Only certain datatypes are allowable"""
        with tempfile.NamedTemporaryFile(suffix='.jp2', mode='wb') as tfile:

            with open(self.jp2file, 'rb') as ifptr:
                tfile.write(ifptr.read())

            # Write L, T, UUID identifier.
            tfile.write(struct.pack('>I4s', 52, b'uuid'))
            tfile.write(b'JpgTiffExif->JP2')

            tfile.write(b'Exif\x00\x00')
            xbuffer = struct.pack('<BBHI', 73, 73, 42, 8)
            tfile.write(xbuffer)

            # We will write just a single tag.
            tfile.write(struct.pack('<H', 1))

            # 2000 is not an allowable TIFF datatype.
            tfile.write(struct.pack('<HHI4s', 271, 2000, 3, b'HTC\x00'))
            tfile.flush()

            with warnings.catch_warnings():
                # Ignore the invalid datatype warnings.
                warnings.simplefilter('ignore')
                j = glymur.Jp2k(tfile.name)

            self.assertEqual(j.box[-1].box_id, 'uuid')

            # Invalid tag, so no data
            self.assertIsNone(j.box[-1].data)
Example #10
0
def convert_j2c_to_qpixmap(uuid, j2c_contents, thumbnail=False):
    '''Converts the raw binary J2C file contents to a Qt pixmap. 
    
    NOTE: A QApplication MUST be instantiated before running this!'''
    
    tmpfile, temp_path = tempfile.mkstemp()
    with os.fdopen(tmpfile, 'wb') as tmpfile:
        tmpfile.write(j2c_contents)

    try:
        img = glymur.Jp2k(temp_path)
        if thumbnail:
            inmem_img = img[::8,::8]
        else:
            inmem_img = img[:]

    except Exception:
        WARN('Could not convert "%s" to pixmap. Texture stream may be incomplete.' % uuid)
        return None

    try:
        os.remove(temp_path)
    except IOError:
        print('Could not remove temp file for "%s".' % uuid)
    
    pixmap = QPixmap(ndarray_to_qimage(inmem_img))

    return pixmap
Example #11
0
    def test_bad_tiff_header_byte_order_indication(self):
        """Only b'II' and b'MM' are allowed."""
        with tempfile.NamedTemporaryFile(suffix='.jp2', mode='wb') as tfile:

            with open(self.jp2file, 'rb') as ifptr:
                tfile.write(ifptr.read())

            # Write L, T, UUID identifier.
            tfile.write(struct.pack('>I4s', 52, b'uuid'))
            tfile.write(b'JpgTiffExif->JP2')

            tfile.write(b'Exif\x00\x00')
            xbuffer = struct.pack('<BBHI', 74, 73, 42, 8)
            tfile.write(xbuffer)

            # We will write just a single tag.
            tfile.write(struct.pack('<H', 1))

            # 271 is the Make.
            tfile.write(struct.pack('<HHI4s', 271, 2, 3, b'HTC\x00'))
            tfile.flush()

            with warnings.catch_warnings():
                # Ignore the warning about the endian order, we test for that
                # elsewhere.
                warnings.simplefilter('ignore')
                jp2 = glymur.Jp2k(tfile.name)

            # We should still get a UUID box out of it.  But we get no data.
            self.assertEqual(jp2.box[-1].box_id, 'uuid')
            self.assertIsNone(jp2.box[-1].data)
Example #12
0
def test_read_data():
    """
    Tests the reading of the JP2 data.
    """
    import glymur
    data = glymur.Jp2k(AIA_193_JP2)[...]
    assert isinstance(data, np.ndarray)
Example #13
0
    def get_dataset(self, key, info):
        """Load a dataset."""
        if self._channel != key['name']:
            return

        logger.debug('Reading %s.', key['name'])
        # FIXME: get this from MTD_MSIL1C.xml
        quantification_value = 10000.
        jp2 = glymur.Jp2k(self.filename)
        bitdepth = 0
        for seg in jp2.codestream.segment:
            try:
                bitdepth = max(bitdepth, seg.bitdepth[0])
            except AttributeError:
                pass

        jp2.dtype = (np.uint8 if bitdepth <= 8 else np.uint16)

        # Initialize the jp2 reader / doesn't work in a multi-threaded context.
        # jp2[0, 0]
        # data = da.from_array(jp2, chunks=CHUNK_SIZE) / quantification_value * 100

        data = da.from_delayed(delayed(jp2.read)(), jp2.shape, jp2.dtype)
        data = data.rechunk(CHUNK_SIZE) / quantification_value * 100

        proj = DataArray(data, dims=['y', 'x'])
        proj.attrs = info.copy()
        proj.attrs['units'] = '%'
        proj.attrs['platform_name'] = self.platform_name
        return proj
Example #14
0
    def test_bad_tag_datatype(self):
        """
        SCENARIO:  A tag with an unrecognized numeric datatype field is found
        in an Exif UUID box.

        EXPECTED RESULT:  A warning is issued.
        """
        with open(self.temp_jp2_filename, mode='wb') as tfile:

            with open(self.jp2file, 'rb') as ifptr:
                tfile.write(ifptr.read())

            # Write L, T, UUID identifier.
            tfile.write(struct.pack('>I4s', 52, b'uuid'))
            tfile.write(b'JpgTiffExif->JP2')

            tfile.write(b'Exif\x00\x00')
            xbuffer = struct.pack('<BBHI', 73, 73, 42, 8)
            tfile.write(xbuffer)

            # We will write just a single tag.
            tfile.write(struct.pack('<H', 1))

            # 2000 is not an allowable TIFF datatype.
            tfile.write(struct.pack('<HHI4s', 271, 2000, 3, b'HTC\x00'))
            tfile.flush()

            with self.assertWarns(UserWarning):
                glymur.Jp2k(tfile.name)
Example #15
0
def load_jp2_file(image_info, type='training'):
    directory = image_info['directory']
    jp2_filename = os.path.join(FLAGS.data_dir, type, directory, 'cropped.jp2')
    try:
        return glymur.Jp2k(jp2_filename).read()
    except Exception as e:
        print(str(e))
        return None
Example #16
0
    def __init__(self, path, **kwargs):
        """
        Initialize the tile class.  See the base class for other available
        parameters.

        :param path: a filesystem path for the tile source.
        """
        super().__init__(path, **kwargs)

        self._largeImagePath = str(self._getLargeImagePath())
        self._pixelInfo = {}
        try:
            self._openjpeg = glymur.Jp2k(self._largeImagePath)
            if not self._openjpeg.shape:
                if not os.path.isfile(self._largeImagePath):
                    raise FileNotFoundError()
                raise TileSourceError(
                    'File cannot be opened via Glymur and OpenJPEG.')
        except (glymur.jp2box.InvalidJp2kError, struct.error):
            raise TileSourceError(
                'File cannot be opened via Glymur and OpenJPEG.')
        except FileNotFoundError:
            if not os.path.isfile(self._largeImagePath):
                raise TileSourceFileNotFoundError(
                    self._largeImagePath) from None
            raise
        glymur.set_option('lib.num_threads', multiprocessing.cpu_count())
        self._openjpegHandles = queue.LifoQueue()
        for _ in range(self._maxOpenHandles - 1):
            self._openjpegHandles.put(None)
        self._openjpegHandles.put(self._openjpeg)
        try:
            self.sizeY, self.sizeX = self._openjpeg.shape[:2]
        except IndexError:
            raise TileSourceError(
                'File cannot be opened via Glymur and OpenJPEG.')
        self.levels = int(self._openjpeg.codestream.segment[2].num_res) + 1
        self._minlevel = 0
        self.tileWidth = self.tileHeight = 2**int(
            math.ceil(
                max(
                    math.log(float(self.sizeX)) / math.log(2) - self.levels +
                    1,
                    math.log(float(self.sizeY)) / math.log(2) - self.levels +
                    1)))
        # Small and large tiles are both inefficient.  Large tiles don't work
        # with some viewers (leaflet and Slide Atlas, for instance)
        if self.tileWidth < self._minTileSize or self.tileWidth > self._maxTileSize:
            self.tileWidth = self.tileHeight = min(
                self._maxTileSize, max(self._minTileSize, self.tileWidth))
            self.levels = int(
                math.ceil(
                    math.log(
                        float(max(self.sizeX, self.sizeY)) / self.tileWidth) /
                    math.log(2))) + 1
            self._minlevel = self.levels - self._openjpeg.codestream.segment[
                2].num_res - 1
        self._getAssociatedImages()
Example #17
0
def dem2jp2(img_data,dem,fname,i,bin_min,bin_max,mk_fits=False):
    #log 10 the data
    datasc=np.log10(img_data+1)
    #take logs of our data range
    logmin=np.log10(dem.dem_min)
    logmax=np.log10(dem.dem_max)
    #floor the data to datamin
    datasc[datasc < logmin]=logmin
    #ceiling the data to datamax
    datasc[datasc > logmax]=logmax
    #scale the data between 0-1
    datasc = ((datasc)-logmin)/(logmax-logmin)
    #convert to unsigned byte
    bytesc=img_as_ubyte(datasc)
    #create the jp2 file
    jp2=glymur.Jp2k(fname+'.jp2',np.flipud(bytesc))
    #create the header
    demxml(dem,fname,i,bin_min,bin_max)
    #load the header
    xmlbox = glymur.jp2box.XMLBox(filename=fname+'.xml')

    jp2.append(xmlbox)
    os.remove(fname+'.xml')
    if mk_fits==True:
        #create the fits
        #dictionary 
        demdict=dem.__dict__.copy()
        #remove keys
        del demdict['data']
        del demdict['edem']
        del demdict['elogt']
        del demdict['temperatures']
        del demdict['chisq']
        del demdict['dn_reg']
        demdict['trange'] = '{:1}-{:1}'.format(dem.minTemp,dem.maxTemp)
        demdict["trangek"] = '{:.2e}-{:.2e}'.format(10**dem.minTemp,10**dem.maxTemp)
        demdict["t_bin"]='{:.2e}-{:.2e}'.format(bin_min,bin_max)
        demdict["DATE-OBS"] = dem.t_obs.isot
        demdict['t_obs']=dem.t_obs.isot+'Z'
        demdict["img_id"] = '{} of {}'.format(i+1,dem.nimg)  
        demdict["img_sc"]='LOG10'
        demdict['github'] ='https://github.com/alasdairwilson/demreg-py'
        demdict["qnty"]='DEM(T)'
        demdict["method"]="Regularised Inversion (Hannah and Kontar 2012)"
        demdict["dem_unit"] = 'cm-5 K-1'
        demdict["contact"] ='*****@*****.**'
        demdict["detector"] = 'demregpy'
        demdict["ctype1"] = 'HPLN-TAN'
        demdict["ctype2"] = 'HPLT-TAN'
        demdict["TELESCOP"] = 'derived-DEM'  
        demdict["instrume"] = 'LOGT {:.2f}-{:.2f}'.format(bin_min,bin_max)
        demdict["filters"] ='AIA94 AIA131 AIA171 AIA193 AIA211 AIA335'
        if os.path.isfile(fname+'.fits'):
            os.remove(fname+'.fits')
        io.fits.write(fname+'.fits',bytesc,demdict)   
        #add the header to the jp2 file.
    return
def create_sift_features_single_tile(tilespecs,
                                     out_fname,
                                     index,
                                     initial_sigma=1.6):

    tilespec = tilespecs[index]

    # load the image
    image_path = tilespec["mipmapLevels"]["0"]["imageUrl"]
    image_path = image_path.replace("file://", "")
    if image_path.endswith(".jp2"):
        import glymur
        img_gray = glymur.Jp2k(image_path)[:]  # load in full resolution
    else:
        if utils.is_cv2():
            img_gray = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
        else:  # OpenCV 3.*
            img_gray = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    print "Computing sift features for image: {}".format(image_path)

    # compute features for the given index
    # detector = cv2.FeatureDetector_create("SIFT")
    # extractor = cv2.DescriptorExtractor_create("SIFT")
    # #print("Detecting keypoints...")
    # kp = detector.detect(img_gray)
    # #print("Computing descriptions...")
    # pts, descs = extractor.compute(img_gray, kp)
    if utils.is_cv2():
        sift = cv2.SIFT(sigma=initial_sigma)
    else:  # OpenCV 3.*
        sift = cv2.xfeatures2d.SIFT_create(sigma=initial_sigma)
    pts, descs = sift.detectAndCompute(img_gray, None)
    if descs is None:
        descs = []
        pts = []

    descs = np.array(descs, dtype=np.uint8)

    # Save the features

    print "Saving {} sift features at: {}".format(len(descs), out_fname)
    with h5py.File(out_fname, 'w') as hf:
        hf.create_dataset("imageUrl",
                          data=np.array(image_path.encode("utf-8"), dtype='S'))
        hf.create_dataset("pts/responses",
                          data=np.array([p.response for p in pts],
                                        dtype=np.float32))
        hf.create_dataset("pts/locations",
                          data=np.array([p.pt for p in pts], dtype=np.float32))
        hf.create_dataset("pts/sizes",
                          data=np.array([p.size for p in pts],
                                        dtype=np.float32))
        hf.create_dataset("pts/octaves",
                          data=np.array([p.octave for p in pts],
                                        dtype=np.float32))
        hf.create_dataset("descs", data=descs)
Example #19
0
def do_one(idx: int, dest: str, psnr: typing.Sequence[int]):
    """
    convert one frame of dcimg to jpeg 2000
    :param idx: index of the frame to convert
    :param dest: path to jpeg 2000 file
    :param psnr: a sequence of DB levels for the compression
    """
    img = dcimg.read_frame(idx)
    glymur.Jp2k(dest, data=img, psnr=psnr)
Example #20
0
def read_jp2_image(filename):
    """ Read data from JPEG2000 file

    :param filename: name of JPEG2000 file to be read
    :type filename: str
    :return: data stored in JPEG2000 file
    """
    image_object = glymur.Jp2k(filename)
    return image_object[:]
Example #21
0
    def test_info_callback_on_write_backwards_compatibility(self):
        """
        SCENARIO:  write to a J2K file while in verbose mode

        EXPECTED RESULT:  verify messages from the library
        """
        j = glymur.Jp2k(self.jp2file)
        with warnings.catch_warnings():
            # Ignore a library warning.
            warnings.simplefilter('ignore')
            tiledata = j.read(tile=0)

        with patch('sys.stdout', new=StringIO()) as fake_out:
            glymur.Jp2k(self.temp_j2k_filename, data=tiledata, verbose=True)
            actual = fake_out.getvalue().strip()

        expected = '[INFO] tile number 1 / 1'
        self.assertEqual(actual, expected)
Example #22
0
    def compressionRatio(self, data, imageName, verbose,
                         precisionFloatingPoint):
        # compressions
        glymur.Jp2k(self.jpeg200Name, data=data)
        glymur.Jp2k(self.jpeg200NameLossy, data=data, cratios=[5])

        # array_buffer = data.tobytes()

        # cv2.imwrite(self.jpegLossy, data)
        # imPillow = Image.new("I", data.T.shape)
        # imPillow.frombytes(array_buffer, 'raw', "I;16")
        # imPillow.save(self.jpegLossy, "JPEG", quality=90)

        bitsNumber = 8 + precisionFloatingPoint

        jpeg_lsBuffer = jpeg_ls.encode(data)
        compressedImage, compressionRatioLZW, compressedSize = self.applyLZWCompressionOnImage(
            data)
        # Sizes.
        originalSize = len(data.tostring()) / 1024
        jpeg2000Size = os.stat(self.jpeg200Name).st_size / 1024
        jpeg200NameLossySize = os.stat(self.jpeg200NameLossy).st_size / 1024
        # jpegLossySize = os.stat(self.jpegLossy).st_size / 1024
        jpegLsSize = len(jpeg_lsBuffer) / 1024
        jpeg2000CompressionRatio = originalSize / jpeg2000Size
        # JpegLossyCompressionRatio = originalSize / jpegLossySize
        JpegLsCompressionRatio = originalSize / jpegLsSize
        Jpeg2000LossyCompressionRatio = originalSize / jpeg200NameLossySize
        if verbose:
            print('Size of uncompressed {0}: {1} KB'.format(
                imageName, originalSize))
            print(
                'compression ratio of JPEG-2000 Lossless encoded {0}: {1} bpp'.
                format(imageName, bitsNumber / jpeg2000CompressionRatio))
            print('compression ratio of JPEG-2000 Lossy encoded {0}: {1} bpp'.
                  format(imageName,
                         bitsNumber / Jpeg2000LossyCompressionRatio))
            # print('compression ratio of JPEG-lossy encoded {0}: {1}'.format(imageName, JpegLossyCompressionRatio))
            print('compression ratio of LZW encoded {0}: {1} bpp'.format(
                imageName, bitsNumber / compressionRatioLZW))
            print('compression ratio of JPEG-LS encoded {0}: {1} bpp'.format(
                imageName, bitsNumber / JpegLsCompressionRatio))

        return bitsNumber / jpeg2000CompressionRatio, bitsNumber / JpegLsCompressionRatio, bitsNumber / compressionRatioLZW
Example #23
0
 def imshow(self):
     """
     Plots preview image with MPL
     """
     dir1 = os.path.join(self.granulePath, 'QI_DATA')
     for f in os.listdir(dir1):
         if f.endswith('.jp2') and f.count('PVI') > 0:
             plt.figure(figsize=(6, 6))
             im = glymur.Jp2k(os.path.join(dir1, f))[:]
             return plt.imshow(im)
Example #24
0
    def test_bad_color_space_specification(self):
        """
        Verify that a warning is issued if the color space method is invalid.

        For JP2, the method must be either 1 or 2.
        """
        jp2 = glymur.Jp2k(self.jp2file)
        jp2.box[2].box[1].method = 3
        with self.assertWarns(UserWarning):
            jp2._validate()
Example #25
0
def write_jp2_image(filename, image):
    """ Write image data to JPEG2000 file

    :param filename: name of JPEG2000 file to write data to
    :type filename: str
    :param image: image data to write to file
    :type image: numpy array
    :return: jp2k object
    """
    return glymur.Jp2k(filename, data=image)
Example #26
0
    def __init__(self, file_path):
        """
        file_path (string): path to single whole-slide image
        """
        super().__init__()
        self.file_ptr = glymur.Jp2k(file_path)
        self.metadata = self.__load_metadata()
        thumbnail = self.__load_thumbnail(1.25)

        data_dict = {"img": thumbnail}
        self.add_data_holder("src", data_dict)
Example #27
0
def get_band(band_suffix, data_dir=None):
    ###Get the raw pixel values for an entire band
    if data_dir is None:
        IMG_DIR = "C:/Users/Rahakami/Downloads/S2A_MSIL1C_20170831T185921_N0205_R013_T10SEH_20170831T191016.SAFE/GRANULE/L1C_T10SEH_A011450_20170831T191016/IMG_DATA/"
        BASE_FN = "T10SEH_20170831T185921_"
        jp2_path = IMG_DIR + BASE_FN + band_suffix + ".jp2"
    else:
        search_pattern = "*_" + band_suffix + ".jp2"
        jp2_path = find_file(search_pattern, data_dir)
    jp2 = glymur.Jp2k(jp2_path)
    # thumbnail = jp2[::2, ::2]#This just skips every 2nd pixel.
    return jp2[:]
Example #28
0
    def test_xml_box_with_encoding_declaration(self):
        """
        Read JP2 file with XML box having encoding declaration
        """
        with tempfile.NamedTemporaryFile(suffix=".jp2") as ofile:
            with open(self.jp2file, mode='rb') as ifile:
                ofile.write(ifile.read())

            # Write the additional box.
            write_buffer = struct.pack('>I4s', int(1777), b'xml ')
            ofile.write(write_buffer)

            relpath = os.path.join('data', 'encoding_declaration.xml')
            xml_file_path = pkg.resource_filename(__name__, relpath)

            with open(xml_file_path, 'rb') as xfptr:
                ofile.write(xfptr.read())

            ofile.flush()
            ofile.seek(0)

            jp2 = glymur.Jp2k(ofile.name)

            # Verify that XML box
            self.assertEqual(jp2.box[-1].box_id, 'xml ')

            namespaces = {
                'gml': "http://www.opengis.net/gml",
                'xsi': "http://www.w3.org/2001/XMLSchema-instance",
            }
            try:
                elts = jp2.box[-1].xml.xpath('//gml:rangeSet',
                                             namespaces=namespaces)
            except AttributeError:
                name = './/{{{ns}}}rangeSet'.format(ns=namespaces['gml'])
                elts = jp2.box[-1].xml.find(name)
            self.assertEqual(len(elts), 1)

            # Write it back out, read it back in.
            with tempfile.NamedTemporaryFile(suffix=".jp2") as ofile2:
                jp2_2 = jp2.wrap(ofile2.name, boxes=jp2.box)

                # Verify that XML box
                self.assertEqual(jp2_2.box[-1].box_id, 'xml ')

                try:
                    elts = jp2.box[-1].xml.xpath('//gml:rangeSet',
                                                 namespaces=namespaces)
                except AttributeError:
                    name = './/{{{ns}}}rangeSet'.format(ns=namespaces['gml'])
                    elts = jp2.box[-1].xml.find(name)

                self.assertEqual(len(elts), 1)
Example #29
0
 def glymurWrapper(self, filename, band):
     # fix for SIIMPC-687, UMW
     if self.config.resolution == 60:
         kwargs = {"tilesize": (192, 192), "prog": "RPCL"}
     elif self.config.resolution == 20:
         kwargs = {"tilesize": (640, 640), "prog": "RPCL"}
     elif self.config.resolution == 10:
         kwargs = {"tilesize": (1024, 1024), "prog": "RPCL"}
     # end fix for SIIMPC-687
     # fix for SIIMPC-558.3, UMW
     glymur.Jp2k(filename, band, **kwargs)
     jp2_L2A = glymur.Jp2k(filename)
     boxes_L2A = jp2_L2A.box
     boxes_L2A.insert(3, self._geobox)
     boxes_L2A[1] = glymur.jp2box.FileTypeBox(
         brand='jpx ', compatibility_list=['jpxb', 'jp2 '])
     file_L3_geo = os.path.splitext(filename)[0] + '_geo.jp2'
     jp2_L2A.wrap(file_L3_geo, boxes=boxes_L2A)
     os.remove(filename)
     os.rename(file_L3_geo, filename)
     # end fix for SIIMPC-558.3
     return
 def jp2k_compress(self, image: np.ndarray) -> typing.List[np.ndarray]:
     """ 对输入图像进行不同level的JPEG2000压缩
     :param image: 输入图像
     :param 不同levelJPEG2000压缩的图像列表
     """
     jp2k_images = []
     for level in self.JP2K_LEVEL:
         jp2k_image = glymur.Jp2k('temp.jp2',
                                  data=image,
                                  cratios=[level, 1])
         jp2k_image.layer = 1
         jp2k_images.append(jp2k_image[:])
     return jp2k_images