Reading a 16-bit greyscale tiff file and saving it as a .png for later

TIFF* tif = TIFFOpen("11111.tif", "r");


    if (tif) {
        uint32 imagelength;
        tsize_t scanline;
        tdata_t buf;
        uint32 row;
        uint32 col;

        ulong grandTotal=0;
        int pixelCount =0;

        QFile dataset("data.dat");
        dataset.open(QIODevice::WriteOnly | QIODevice::Text);
        QTextStream textStream( &dataset );
        QList<int> intData;


        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
        scanline = TIFFScanlineSize(tif);
        buf = _TIFFmalloc(scanline);
        for (row = 0; row < imagelength; row++)
        {
            TIFFReadScanline(tif, buf, row);
            uchar *vals = static_cast<uchar*>(buf);
            for (col = 0; col < (scanline/2); col++) {
                int first = vals[col*2];
                int second = vals[(col*2)+1];
                int combine = first + (second * 256);

                textStream<<QString::number(combine)<<"\n";

                grandTotal+= combine;
                pixelCount++;

                intData.append(combine);
            }
            //qDebug()<<"Scanline Size: "<<scanline;


        }
        dataset.close();;
        _TIFFfree(buf);
        TIFFClose(tif);


        uint average = grandTotal / pixelCount;
        ulong variance=0;
        for(int i: intData) {
            int diff = average - i;
            variance += (diff*diff);
        }
        qreal stdev = sqrt( variance / pixelCount);

        int low = (int) (average - (1.5 * stdev));
        int high = (int) (average + (1.5 * stdev));
        qreal range = high-low;
        qDebug()<<"Averge: "<<average;
        qDebug()<<"variance: "<<variance;
        qDebug()<<"stdev: "<<stdev;
        qDebug()<<"low: "<<low;
        qDebug()<<"high: "<<high;
        qDebug()<<"range: "<<range;


        int i=0;

        QImage makeMe(scanline/2,imagelength,QImage::Format_RGB32);
        qDebug()<<makeMe.height() * makeMe.width() <<"="<< intData.length();

        for(int y=0;y<makeMe.height();y++) {
            for(int x=0;x<makeMe.width();x++) {
                int value = intData.at(i++);
                if(value< low) {
                    value = 0;
                }
                else if(value > high) {
                    value = 255;
                }
                else {
                    qreal fraction = (value - low)/range;
                    value =(int) (fraction * 255);
                    //qDebug()<<value;
                }
                makeMe.setPixelColor(x,y,QColor(value,value,value));
            }
        }

        makeMe.invertPixels(QImage::InvertRgb);
        makeMe.save("makeMe.png");

    }

Leave a Reply

Your email address will not be published. Required fields are marked *