[英]QImage: Read 16-bit grayscale TIFF (Qt, C++)
我想使用C ++,Qt和libtiff讀取16位灰度圖像。 我創建了readTiff函數(如下),該函數從tiff讀取數據到QImage。 但是,存在QImage 5.5不支持16位灰度的問題 。 如果我使用RGB16,我只會得到噪音。
如何破解QImage以支持Format_Grayscale16或將數據轉換為Format_Grayscale8?
/**
* @brief Reads TIFF image
* @param path
* @return QImage
*/
QImage EdsImporter::readTiff(const QString &path) const {
// Loads tiff file
TIFF* tiff = TIFFOpen(path.toStdString().c_str(), "r");
if (!tiff) {
QString msg = "Failed to open TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
// Temporary variables
uint32 width, height;
tsize_t scanlength;
// Read dimensions of image
if (TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width) != 1) {
QString msg = "Failed to read width of TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
if (TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height) != 1) {
QString msg = "Failed to read height of TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
// Number of bytes in a decoded scanline
scanlength = TIFFScanlineSize(tiff);
QImage image(width, height, QImage::Format_RGB16);
// TEMPORARY: Save to PNG for preview
image.save("tiff/" + StringUtils::random() + ".png", "PNG");
if (image.isNull() || scanlength != image.bytesPerLine()) {
TIFFClose(tiff);
QString msg = "Failed to create QImage from TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
// Read image data
for (uint32 y = 0; y < height; y++) {
TIFFReadScanline(tiff, image.scanLine(y), y);
}
TIFFClose(tiff);
return image;
}
試試這個應該工作(我沒有測試過,只是從頭開始寫)
QImage convertGray16TifToQImage(TIFF *tif) {
// Temporary variables
uint32 width, height;
// Read dimensions of image
if (TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width) != 1) {
QString msg = "Failed to read width of TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
if (TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height) != 1) {
QString msg = "Failed to read height of TIFF: '" + path + "'";
throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__);
}
QImage result(width, height, QImage::Format_Grayscale8);
QVarLengthArray<quint16, 1024> src(width);
for (uint32 y=0; y<height; ++y) {
TIFFReadScanline(tiff, src.data(), y, 0);
quint8 *dst = (quint8 *)result.scanLine(y);
for (uint32 x=0; x<width; ++x) {
dst[x] = src[x]>>8; // here you have a room for tweaking color range usage
}
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.