【问题标题】:Reading .tif images in C using libtiff returns one column使用 libtiff 在 C 中读取 .tif 图像会返回一列
【发布时间】:2018-12-31 22:06:32
【问题描述】:

我想使用“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;

}

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

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

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

【问题讨论】:

    标签: c libtiff


    【解决方案1】:

    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");
    }
    

    【讨论】:

    • 谢谢你成功了! ,我之前尝试过同样的事情,但我没有添加“data++”。我相信我现在对代码的实际工作方式有了清晰的了解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2021-08-30
    • 2019-01-02
    • 2014-01-17
    • 2018-11-26
    相关资源
    最近更新 更多