一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

尝试使用libtiff将一个16位的灰度tif图像转为OpenCV中对应的Mat格式并显示出来,参考代码如下:

 1 void tiff_test()
 2 {
 3     libtiff::TIFF *image;
 4     uint32_t width = 0, height = 0;
 5     uint16_t ncn = 0;
 6     uint16_t bitsPer = 0;
 7     uint16_t *pData;
 8     if((image = libtiff::TIFFOpen("/Users/Ko/brake/Tiff/brake1_height.tif",  "r")) == NULL)
 9     {
10         cout << "not a tiff" << endl;
11         exit(1);
12     } else {
13         cout << "tiff loaded" << endl;
14     }
15   
16     libtiff::TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);
17     libtiff::TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);
18     libtiff::TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &ncn);
19     libtiff::TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bitsPer);
20     pData = (uint16_t *)libtiff::_TIFFmalloc(width * height * bitsPer);
21     if(pData != NULL)
22     {
23         
24     }
25     cout << "tiff width:" << width << endl;
26     cout << "tiff length:" << height << endl;
27     cout << ncn << endl;
28     cout << "bitsPer:" << bitsPer << endl;
29     cout << "scanlinesize:" << libtiff::TIFFScanlineSize(image) << endl;
30     for(int i = 0; i < height; i++)
31     {
32         libtiff::TIFFReadScanline(image, pData + i * width, i);
33     }
34     Mat M(height, width, CV_16UC1, Scalar(0));
35     for(int i = 0; i < height; i++)
36     {
37         for(int j = 0; j < width; j++)
38         {
39             M.at<uint16_t>(i,j) = pData[j + i * width];
40         }
41     }
42     imshow("result", M);
43     libtiff::_TIFFfree(pData);
44     libtiff::TIFFClose(image);
45 }

 

posted on 2020-12-07 13:46  一杯清酒邀明月  阅读(842)  评论(1编辑  收藏  举报