尝试使用libtiff将一个16位的灰度tif图像转为OpenCV中对应的Mat格式并显示出来,参考代码如下:
void tiff_test()
{
libtiff::TIFF *image;
uint32_t width = 0, height = 0;
uint16_t ncn = 0;
uint16_t bitsPer = 0;
uint16_t *pData;
if((image = libtiff::TIFFOpen("/Users/Ko/brake/Tiff/brake1_height.tif", "r")) == NULL)
{
cout << "not a tiff" << endl;
exit(1);
} else {
cout << "tiff loaded" << endl;
}
libtiff::TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);
libtiff::TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);
libtiff::TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &ncn);
libtiff::TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bitsPer);
pData = (uint16_t *)libtiff::_TIFFmalloc(width * height * bitsPer);
if(pData != NULL)
{
}
cout << "tiff width:" << width << endl;
cout << "tiff length:" << height << endl;
cout << ncn << endl;
cout << "bitsPer:" << bitsPer << endl;
cout << "scanlinesize:" << libtiff::TIFFScanlineSize(image) << endl;
for(int i = 0; i < height; i++)
{
libtiff::TIFFReadScanline(image, pData + i * width, i);
}
Mat M(height, width, CV_16UC1, Scalar(0));
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
M.at<uint16_t>(i,j) = pData[j + i * width];
}
}
imshow("result", M);
libtiff::_TIFFfree(pData);
libtiff::TIFFClose(image);
}