API reference

This file is part of glymur, a Python interface for accessing JPEG 2000.

http://glymur.readthedocs.org

Copyright 2013 John Evans

License: MIT

class glymur.Jp2kr(filename: str | Path, verbose: bool = False, **kwargs)

Read JPEG 2000 files.

Attributes:
boxsequence

List of top-level boxes in the file. Each box may in turn contain its own list of boxes. Will be empty if the file consists only of a raw codestream.

filenamestr

The path to the JPEG 2000 file.

pathPath

The path to the JPEG 2000 file.

Examples

>>> jfile = glymur.data.nemo()
>>> jp2 = glymur.Jp2kr(jfile)
>>> jp2.shape
(1456, 2592, 3)
>>> image = jp2[:]
>>> image.shape
(1456, 2592, 3)

Read a lower resolution thumbnail.

>>> thumbnail = jp2[::2, ::2]
>>> thumbnail.shape
(728, 1296, 3)

Make use of OpenJPEG’s thread support

>>> import time
>>> jp2file = glymur.data.nemo()
>>> jp2 = glymur.Jp2k(jp2file)
>>> t0 = time.time(); data = jp2[:]; t1 = time.time()
>>> t1 - t0 
0.9024193286895752
>>> glymur.set_option('lib.num_threads', 4)
>>> t0 = time.time(); data = jp2[:]; t1 = time.time()
>>> t1 - t0 
0.4060473537445068
property codestream

Metadata for JP2 or J2K codestream header.

Examples

>>> from glymur import Jp2kr
>>> jp2file = glymur.data.nemo()
>>> c = Jp2kr(jp2file).codestream
>>> print(c.segment[0])
SOC marker segment @ (85, 0)
>>> len(c.segment)
5
property decoded_components

If true, decode only these components. The MCT will not be used. List or scalar or None (default).

Examples

>>> from glymur import Jp2kr
>>> j = Jp2kr(glymur.data.nemo())
>>> rgb = j[:]
>>> print(rgb.shape)
(1456, 2592, 3)
>>> j.decoded_components = 0
>>> comp0 = j[:]
>>> print(comp0.shape)
(1456, 2592)
property dtype

Datatype of the image.

Examples

>>> from glymur import Jp2kr
>>> jp2file = glymur.data.nemo()
>>> j = Jp2kr(jp2file)
>>> j.dtype
<class 'numpy.uint8'>
get_codestream(header_only=True)

Retrieve codestream.

This differs from the codestream property in that segment metadata that lies past the end of the codestream header can be retrieved.

Parameters:
header_onlybool, optional

If True, only marker segments in the main header are parsed. Supplying False may impose a large performance penalty.

Returns:
Codestream

Object describing the codestream syntax.

Examples

>>> jfile = glymur.data.nemo()
>>> jp2 = glymur.Jp2k(jfile)
>>> codestream = jp2.get_codestream(header_only=False)
>>> print(codestream.segment[1])
SIZ marker segment @ (87, 47)
    Profile:  no profile
    Reference Grid Height, Width:  (1456 x 2592)
    Vertical, Horizontal Reference Grid Offset:  (0 x 0)
    Reference Tile Height, Width:  (1456 x 2592)
    Vertical, Horizontal Reference Tile Offset:  (0 x 0)
    Bitdepth:  (8, 8, 8)
    Signed:  (False, False, False)
    Vertical, Horizontal Subsampling:  ((1, 1), (1, 1), (1, 1))
>>> print(len(codestream.segment))
12
>>> print(codestream.segment[-1])
EOC marker segment @ (1132371, 0)
property ignore_pclr_cmap_cdef

If true, ignore the pclr, cmap, or cdef boxes during any color transformation. Why would you wish to do that? In the immortal words of Critical Drinker, don’t know!

Defaults to false.

Examples

>>> from glymur import Jp2kr
>>> jpxfile = glymur.data.jpxfile()
>>> j = Jp2kr(jpxfile)
>>> d = j[:]
>>> print(d.shape)
(1024, 1024, 3)
>>> j.ignore_pclr_cmap_cdef = True
>>> d = j[:]
>>> print(d.shape)
(1024, 1024)
property layer

Zero-based number of quality layer to decode. Defaults to 0, the highest quality layer.

property ndim

Number of image dimensions.

Examples

>>> from glymur import Jp2kr
>>> jp2file = glymur.data.nemo()
>>> j = Jp2kr(jp2file)
>>> j.ndim
3
parse(force=False)

Deprecated since version 0.15.0.

read_bands(rlevel=0, layer=0, area=None, tile=None, verbose=False, ignore_pclr_cmap_cdef=False)

Read a JPEG 2000 image.

The only time you should ever use this method is when the image has different subsampling factors across components. Otherwise you should use numpy-style slicing.

Parameters:
layerint, optional

Number of quality layer to decode.

rlevelint, optional

Factor by which to rlevel output resolution.

areatuple, optional

Specifies decoding image area, (first_row, first_col, last_row, last_col)

tileint, optional

Number of tile to decode.

ignore_pclr_cmap_cdefbool

Whether or not to ignore the pclr, cmap, or cdef boxes during any color transformation. Defaults to False.

verbosebool, optional

Print informational messages produced by the OpenJPEG library.

Returns:
list

List of the individual image components.

See also

read

read JPEG 2000 image

Examples

>>> jfile = glymur.data.nemo()
>>> jp = glymur.Jp2k(jfile)
>>> components_lst = jp.read_bands(rlevel=1)
property shape

Dimensions of full resolution image.

Examples

>>> jp = glymur.Jp2kr(glymur.data.nemo())
>>> print(jp.shape)
(1456, 2592, 3)
property tilesize

Height and width of the image tiles.

Examples

>>> jp = glymur.Jp2kr(glymur.data.nemo())
>>> print(jp.shape)
(1456, 2592, 3)
>>> print(jp.tilesize)
(1456, 2592)
property verbose

If true, print informational messages produced by the OpenJPEG library. Defaults to false.

Examples

>>> import skimage
>>> j = glymur.Jp2k('moon.jp2', tilesize=[256, 256], verbose=True)
>>> j[:] = skimage.data.moon()
[INFO] tile number 1 / 4
[INFO] tile number 2 / 4
[INFO] tile number 3 / 4
[INFO] tile number 4 / 4

This file is part of glymur, a Python interface for accessing JPEG 2000.

http://glymur.readthedocs.org

Copyright 2013 John Evans

License: MIT

class glymur.Jp2k(filename: str | pathlib.Path, data: np.ndarray | None = None, capture_resolution: Tuple[int, int] | None = None, cbsize: Tuple[int, int] | None = None, cinema2k: int = 0, cinema4k: bool = False, colorspace: str | None = None, cratios: Tuple[int, ...] | None = None, display_resolution: Tuple[int, int] | None = None, eph: bool = False, grid_offset: Tuple[int, int] | None = None, irreversible: bool = False, mct: bool | None = None, modesw: int = 0, numres: int = 6, plt: bool = False, prog: str | None = None, psizes: List[Tuple[int, int]] | None = None, psnr: Tuple[int, ...] | None = None, shape: Tuple[int, int, ...] | None = None, sop: bool = False, subsam: Tuple[int, int] | None = None, tilesize: Tuple[int, int] | None = None, tlm: bool = False, verbose: bool = False)

Write JPEG 2000 files (and optionally read them as well).

Parameters:
filenamestr or path

The path to JPEG 2000 file.

datanp.ndarray, optional

Image data to be written to file.

shapeTuple[int, int, …], optional

Size of image data, only required when image_data is not provided.

capture_resolutionTuple[int, int], optional

Capture solution (VRES, HRES). This appends a capture resolution box onto the end of the JP2 file when it is created.

cbsizeTuple[int, int], optional

Code block size (NROWS, NCOLS)

cinema2kint, optional

Frames per second, either 24 or 48.

cinema4kbool, optional

Set to True to specify Cinema4K mode, defaults to false.

colorspace{‘rgb’, ‘gray’}, optional

The image color space. If not supplied, it will be inferred.

cratiosTuple[int, …], optional

Compression ratios for successive layers.

display_resolutionTuple[int, int], optional

Display solution (VRES, HRES). This appends a display resolution box onto the end of the JP2 file when it is created.

ephbool, optional

If true, write EPH marker after each header packet.

grid_offsetTuple[int, int], optional

Offset (DY, DX) of the origin of the image in the reference grid.

irreversiblebool, optional

If true, use the irreversible DWT 9-7 transform.

mctbool, optional

Usage of the multi component transform to write an image. If not specified, defaults to True if the color space is RGB, false if the color space is grayscale.

modeswint, optional
mode switch

1 = BYPASS(LAZY) 2 = RESET 4 = RESTART(TERMALL) 8 = VSC 16 = ERTERM(SEGTERM) 32 = SEGMARK(SEGSYM)

numresint, optional

Number of resolutions, defaults to 6. This number will be equal to the number of thumbnails plus the original image.

pltbool, optional

Generate PLT markers.

prog{‘LRCP’, ‘RLCP’, ‘RPCL’, ‘PCRL’, ‘CPRL’}, optional

Progression order. If not specified, the chosen progression order will be ‘CPRL’ if either cinema2k or cinema4k is specified, otherwise defaulting to ‘LRCP’.

psizesList[Tuple[int, int]], optional

Precinct sizes, each precinct size tuple is defined as (height, width).

psnrTuple[int, …] or None

Different PSNR for successive layers. If the last layer is desired to be lossless, specify 0 for the last value.

sopbool, optional

If true, write SOP marker before each packet.

subsamTuple[int, int], optional

Subsampling factors (dy, dx).

tilesizeTuple[int, int], optional

Tile size in terms of (numrows, numcols), not (X, Y).

tlmbool, optional

Generate TLM markers.

verbosebool, optional

Print informational messages produced by the OpenJPEG library.

append(box)

Append a metadata box to the JP2 file. This will not result in a file-copy operation. Only XML UUID (XMP), or ASOC boxes can be appended at this time.

Parameters:
boxJp2Box

Instance of a JP2 box.

Examples

>>> import io, shutil, lxml.etree as ET
>>> _ = shutil.copyfile(glymur.data.nemo(), 'new-nemo.jp2')
>>> j = glymur.Jp2k('new-nemo.jp2')
>>> b = io.BytesIO(b'''
... <info>
...     <city>Nashville</city>
...     <city>Knoxville</city>
...     <city>Whoville</city>
... </info>
... ''')
>>> doc = ET.parse(b)
>>> xmlbox = glymur.jp2box.XMLBox(xml=doc)
>>> j.append(xmlbox)
>>> glymur.set_option('print.codestream', False)
>>> print(j)
File:  new-nemo.jp2
JPEG 2000 Signature Box (jP  ) @ (0, 12)
    Signature:  0d0a870a
File Type Box (ftyp) @ (12, 20)
    Brand:  jp2 
    Compatibility:  ['jp2 ']
JP2 Header Box (jp2h) @ (32, 45)
    Image Header Box (ihdr) @ (40, 22)
        Size:  [1456 2592 3]
        Bitdepth:  8
        Signed:  False
        Compression:  wavelet
        Colorspace Unknown:  False
    Colour Specification Box (colr) @ (62, 15)
        Method:  enumerated colorspace
        Precedence:  0
        Colorspace:  sRGB
Contiguous Codestream Box (jp2c) @ (77, 1132296)
XML Box (xml ) @ (1132373, 102)
    <info>
        <city>Nashville</city>
        <city>Knoxville</city>
        <city>Whoville</city>
    </info>
finalize(force_parse=False)

For now, the only remaining tasks are to possibly parse the file and to possibly write out a ResolutionBox. There could be other possibilities in the future.

Parameters:
forcebool

If true, then run finalize operations

get_tilewriters()

Return an object that facilitates writing tile by tile.

The tiles are written out left-to-right, tile-row-by-tile-row. You must have image data ready to feed each tile writer, and you cannot skip a tile.

You can use this method to write extremely large images that cannot fit into memory, tile by tile.

Examples

>>> import skimage.data
>>> img = skimage.data.moon()
>>> print(img.shape)
(512, 512)
>>> shape = img.shape[0] * 2, img.shape[1] * 2
>>> tilesize = (img.shape[0], img.shape[1])
>>> j = Jp2k('moon-4.jp2', shape=shape, tilesize=tilesize)
>>> for tw in j.get_tilewriters():
...     tw[:] = img
>>> j = Jp2kr('moon-4.jp2')
>>> print(j.shape)
(1024, 1024)
wrap(filename, boxes=None)

Create a new JP2/JPX file wrapped in a new set of JP2 boxes.

This method is primarily aimed at wrapping a raw codestream in a set of of JP2 boxes (turning it into a JP2 file instead of just a raw codestream), or rewrapping a codestream in a JP2 file in a new “jacket” of JP2 boxes. Wrapping a raw codestream preserves the internal structure of the codestream, whereas simply writing it back out by invoking the Jp2k constructor might rewrite the internal structure.

Parameters:
filenamestr

JP2 file to be created from a raw codestream.

boxeslist

JP2 box definitions to define the JP2 file format. If not provided, a default “”jacket” is assumed, consisting of JP2 signature, file type, JP2 header, and contiguous codestream boxes. A JPX file rewrapped without the boxes argument results in a JP2 file encompassing the first codestream.

Returns:
Jp2k

Newly wrapped Jp2k object.

Examples

>>> j2c = glymur.Jp2k(glymur.data.goodstuff())
>>> jp2 = j2c.wrap('new-goodstuff.jp2')
>>> glymur.set_option('print.short', True)
>>> print(jp2)
File:  new-goodstuff.jp2
JPEG 2000 Signature Box (jP  ) @ (0, 12)
File Type Box (ftyp) @ (12, 20)
JP2 Header Box (jp2h) @ (32, 45)
    Image Header Box (ihdr) @ (40, 22)
    Colour Specification Box (colr) @ (62, 15)
Contiguous Codestream Box (jp2c) @ (77, 115228)