Search code examples
c++floating-pointtifflibtiffimage-conversion

Can LibTIFF be used with C++ to get the float values of images?


I read here that LibTIFF can display floating point TIFFs. However, I would like to load an image, then get the float values as an array.

Is this possible to do using LibTIFF?

Example TIFF

EDIT: I am using RHEL 6.


Solution

  • If you want to do it with pure libTIFF, your code might look something like this - note that I have not done much error checking so as not to confuse the reader of the code - but you should check that the image is of type float, and you should check the results of memory allocations and you probably shouldn't use malloc() like I do but rather the new C++ methods of memory allocation - but the concept is hopefully clear and the code generates the same answers as my CImg version...

    #include "tiffio.h"
    #include <cstdio>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
      TIFF* tiff = TIFFOpen("image.tif","r");
      if (!tiff) {
        cerr << "Failed to open image" << endl;
        exit(1);
      }
    
      uint32 width, height;
      tsize_t scanlength;
    
      // Read dimensions of image
      if (TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) {
        cerr << "Failed to read width" << endl;
        exit(1);
      }
      if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH, &height) != 1) {
        cerr << "Failed to read height" << endl;
        exit(1);
      }
    
      scanlength = TIFFScanlineSize(tiff);
    
      // Make space for image in memory
      float** image= (float**)malloc(sizeof (float*)*height);
    
      cout << "Dimensions: " << width << "x" << height << endl;
      cout << "Line buffer length (bytes): " << scanlength << endl;
    
      // Read image data allocating space for each line as we get it
      for (uint32 y = 0; y < height; y++) {
        image[y]=(float*)malloc(scanlength);
        TIFFReadScanline(tiff,image[y],y);
        cout << "Line(" << y << "): " << image[y][0] << "," << image[y][1] << "," << image[y][2] << endl;
      }
      TIFFClose(tiff);
    
    }
    

    Sample Output

    Dimensions: 512x256
    Line buffer length (bytes): 6144
    Line(0): 3.91318e-06,0.232721,128
    Line(1): 0.24209,1.06866,128
    Line(2): 0.185419,2.45852,128
    Line(3): 0.141297,3.06488,128
    Line(4): 0.346642,4.35358,128
    ...
    ...
    

    By the way...

    I converted your image to a regular JPEG using ImageMagick in the Terminal at the command line as follows:

    convert map.tif[0] -auto-level result.jpg
    

    enter image description here