[GIS] Creating JP2 with gdal in python

gdaljpeg 2000python

I'm using jp2 with no problem for reading and can create a copy with createcopy, but when I try to create jp2, it fails.

driver = gdal.GetDriverByName("JP2OpenJPEG")
dst_ds = driver.Create("test.jp2",xsize=img.RasterXSize, ysize=img.RasterYSize,bands=1,eType=gdal.GDT_UInt16)

Same code but using GTiff driver works ok:

driver = gdal.GetDriverByName("GTiff")
dst_ds = driver.Create("test.jp2",xsize=img.RasterXSize, ysize=img.RasterYSize,bands=1,eType=gdal.GDT_UInt16)

In the first case dst_ds is none, in the second one I get a correctly created dataset.

Note: img is another JP2 file opened without problem for reading.

Originally I was doing a createcopy, update some pixel values, doing a WriteArray, and flushing but I can see the changes reflected in de destination file, so I decide to create from scratch.

Is there a write limitation in the driver? I'm doing something wrong?

UPDATE 1:

adding the code:

if(dst_ds is None):
   print(gdal.GetLastErrorMsg())

I'm getting the message:
GDALDriver::Create() … no create method implemented for this format.

It does not look good….

Best Answer

You can check what operations some format supports with gdalinfo

gdalinfo --format JP2OopenJPEG
Format Details:
  Short Name: JP2OpenJPEG
  Long Name: JPEG-2000 driver based on OpenJPEG library
  Supports: Raster
  Supports: Vector
  Extensions: jp2 j2k
  Mime Type: image/jp2
  Help Topic: frmt_jp2openjpeg.html
  Supports: Open() - Open existing dataset.
  Supports: CreateCopy() - Create dataset by copying another.
  Supports: Virtual IO - eg. /vsimem/
  Creation Datatypes: Byte Int16 UInt16 Int32 UInt32

So no support for Create() in JP2OpenJPEG as you have noticed. I believe that JPEG2000 belongs to those "sequential write once formats" which are mentioned in http://www.gdal.org/classGDALDriver.html.

Note that many sequential write once formats (such as JPEG and PNG) don't implement the Create() method but do implement this CreateCopy() method. If the driver doesn't implement CreateCopy(), but does implement Create() then the default CreateCopy() mechanism built on calling Create() will be used. So to test if CreateCopy() is available, you can test if GDAL_DCAP_CREATECOPY or GDAL_DCAP_CREATE is set in the GDAL metadata.

It is intended that CreateCopy() will often be used with a source dataset which is a virtual dataset allowing configuration of band types, and other information without actually duplicating raster data (see the VRT driver). This is what is done by the gdal_translate utility for example.

Related Question