c - 使用 libtiff 在 C 中读取 .tif 图像返回一列

标签 c libtiff

我想使用“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("%d\n",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]= %d\n im[2] = %d \n im[3] = %d \n im[286628] = %d\n",im[0],im[1],im[2],im[286627]);
        _TIFFfree(buf);
        TIFFClose(tif);
        free(im);
    }
    printf("num of cols= %d\n",count);
    printf("num of rows = %d\n",count2);//both counts print col size
    printf("width = %d\n",width); //prints row size

    return 0;

}

在嵌套的for循环中,如果我添加括号,循环会迭代正确的像素数 (对于此示例 #of-pixels = 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");
}

关于c - 使用 libtiff 在 C 中读取 .tif 图像返回一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991765/

相关文章:

clock_gettime() 仍然不是单调的 - 替代方案?

c 如何从另一个结构变量初始化结构数组成员

javascript - javascript 中的 >>> 0 是什么?

c++ - 如何解决警告/usr/bin/ld : warning: libtiff. so.4,需要/home/user/libs/opencv/lib/libopencv_highgui.so,可能与libtiff.so.5冲突?

c - 68HC11 上使用 4 字节数字的斐波那契数列

c - libuv fs 读取文件再打印一次

c - 如何在不使用 c 中的已知函数的情况下舍入到最接近的整数?

c++ - 如何读取自定义 TIFF 标签(无 TIFFFieldInfo)

c++ - 在 C++ 中使用 libtiff 写入图像时出现问题,在 TIFFScanlineSize 中出现整数溢出

c++ - 我如何使用 Qt 查看大图像?