使用 libtiff 读取 C 语言中的.tif图像将返回一列



我想使用"libtiff"库从".tiff"图像中读取u8位像素强度值。 我遇到了这段代码并对其进行了修改以根据需要读取 8 位值,并仅返回一列的正确值。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include "tiffio.h"
#define imsize 286628
 int count;
 int count2;
 uint8* im;
 uint32 imagelength;
 uint32 width;
int main(){
im = (uint8*)malloc(imsize*sizeof(uint8));
TIFF* tif = TIFFOpen("image1.tif", "r");
    if (tif) {
        tsize_t scanline;
        tdata_t buf;
        uint32 row;
        uint32 col;

        uint16 nsamples;
        TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &nsamples);
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
        TIFFGetField(tif,TIFFTAG_IMAGEWIDTH,&width);
        scanline = TIFFScanlineSize(tif);
        buf = _TIFFmalloc(scanline);
        uint8* data;
        for (row = 0; row < imagelength; row++)
        {
            TIFFReadScanline(tif, buf, row,1);
            count2++;
            for (col = 0; col < scanline; col++)
                data = (uint8*)buf;
                //printf("%dn",col); remains the same not incrementing
                printf("%d ", *data);//printing for testing need only to copy to an array to access by index
                im[count] = *data;
                count++;
            printf("n");
        }
        printf("im[1]= %dn im[2] = %d n im[3] = %d n im[286628] = %dn",im[0],im[1],im[2],im[286627]);
        _TIFFfree(buf);
        TIFFClose(tif);
        free(im);
    }
    printf("num of cols= %dn",count);
    printf("num of rows = %dn",count2);//both counts print col size
    printf("width = %dn",width); //prints row size
    return 0;
}

在嵌套的forloop中,如果我添加括号,循环迭代正确的像素数(对于此示例,#of 像素 = 286628,547x524 图像),但值不正确。如果我删除括号,我会得到正确的值,但对于第一列(只有 547 个值)。

需要进行哪些更改才能正确迭代所有像素?

注意:我正在尝试获取一个值为 matlabs "imread()" 的矩阵

col循环中,每列使用data = (uint8*)buf;执行完全相同的操作,这似乎是第一列的数据。环也缺少{大括号}

移动线条

data = (uint8*)buf;

列循环外部,并在循环内递增。

for (row = 0; row < imagelength; row++)
{
    TIFFReadScanline(tif, buf, row,1);
    count2++;
    data = (uint8*)buf;                     // move up
    for (col = 0; col < scanline; col++)
    {                                       // add braces
        printf("%d ", *data);
        im[count] = *data;
        count++;
        data++;                             // increment buffer pointer
    }
    printf("n");
}

最新更新