如何在libtiff中加载灰度tiff并获得像素强度数组?

The*_*aly 6 c tiff pixel libtiff

我想要更多地了解图像,而且我遇到了很多麻烦.从使用matlab,我有使用imread('test.tif')的经验,并获得一个漂亮的行与列的矩阵,其中每个像素的强度为整数.因此,720 x 250图像将提供720 x 250矩阵,其中每个单元格包含像素的强度,范围为0-255(取决于数据类型).所以,0是黑色,255是白色.

它非常简单,非常有意义.现在我试图使用libtiff,我真的很挣扎.我想做同样的事情 - 访问那些像素,我只是无法得到它.

我有以下代码:

int main(int argc, char *argv[]){
  TIFF* tif = TIFFOpen( argv[1], "r");
    FILE *fp = fopen("test2.txt", "w+");

  if (tif) {
      int * buf;
      tstrip_t strip;
      uint32* bc;
      uint32 stripsize;
  TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
  stripsize = bc[0];
  buf   = _TIFFmalloc(stripsize);
  for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++ ) {
      if( bc[strip] > stripsize) {
          buf = _TIFFrealloc(buf, bc[strip]);
          stripsize = bc[strip];
      }
      TIFFReadRawStrip(tif, strip, buf, bc[strip]);
  }
  int i;
  for (i=0; i<stripsize; i++) {
      if ( i % 960 ==0 )
          fprintf(fp, "\n");
      fprintf(fp,"%d ",  buf[i]);
  }
  _TIFFfree(buf);
  TIFFClose(tif);
  }
  exit(0);
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了完全没有意义的结果 - 只是完全没有数字.没有像我在matlab中加载图像时看到的数字.

我怎样才能简单地访问像素值,并查看它们?

非常感谢.

Bob*_*sky 6

我想你应该阅读使用TIFF库的文章.它包含足够的信息来开始使用libtiff.

以下是一些读取每个样本的图像扫描线和打印值的代码.

main()
{
    TIFF* tif = TIFFOpen("myfile.tif", "r");
    if (tif) {
        uint32 imagelength;
        tsize_t scanline;
        tdata_t buf;
        uint32 row;
        uint32 col;

        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
        scanline = TIFFScanlineSize(tif);
        buf = _TIFFmalloc(scanline);
        for (row = 0; row < imagelength; row++)
        {
            TIFFReadScanline(tif, buf, row);
            for (col = 0; col < scanline; col++)
                printf("%d ", buf[col]);

            printf("\n");
        }
        _TIFFfree(buf);
        TIFFClose(tif);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 错误:函数“TIFFReadScanline”的参数太少 (2认同)