gpt4 book ai didi

C++图像数组类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:59:02 25 4
gpt4 key购买 nike

我正在使用 C++ 处理适合的图像。这种格式可以容纳 8/16/32 位整数和 32/64 位 float 组。像素大小(可变类型)包含在标题标志中。当我使用 cfitsio 库 [http://heasarc.gsfc.nasa.gov/fitsio/] 读取其中一张图像时,我得到一个包含图像所有像素的字符数组:

char* array = new char[npix*bytepix]; // bytepix is the number of bytes per pixel
fits_read_img(infptr, datatype, first, npix, &nulval, lArray, &anynul, &status);

然后我可以通过类型转换获得像素的“真实”值。 IE。要获取 32 位整数的第 i 个像素的值,我会这样做:

int32_t pixelValue = ((int32_t*) lArray)[i];

我想知道通常处理这个问题的最紧凑的方法是什么,因为我不知道编写代码时像素类型是什么。

我目前做的是这样的:

switch(bytepix){
case 1:{
int8_t *vecVal = ((int8_t*) array );
}
break;
case 2:{
int16_t *vecVal = ((int16_t*) array );
}
break;
case 4:{
int32_t *vecVal = ((int32_t*) array );
}
break;
case 8:{
int64_t *vecVal = ((int64_t*) array );
}
break;
default:
cout << "error\n";
break;
}
}

这显然很丑陋而且不太灵活。

非常感谢您的帮助!

最佳答案

您尝试做的事情叫做泛型编程。这是一个基本概念,它将算法及其运行的类型分开。它在 C++ 中通过模板函数模板类 得到支持,整个 C++ 标准模板库都基于它。

基本上,独立于 FITS 像素大小实现您的处理函数:

template<typename Pixel>
void ProcessImage(Pixel *array, const int arr_length) {
...
}

然后用相应的像素大小调用它:

...
case 1:
ProcessImage<int8_t>(reinterpret_cast<int8_t *>(array), arr_length);
break;
case 2:
ProcessImage<int16_t>(reinterpret_cast<int16_t *>(array), arr_length);
break;
...

几个想法:

  1. 您使用 C++,但编写的是 C 风格的代码。我建议您熟悉 C++ STL、容器和算法,它们正是图像处理所需要的。
  2. 有一个 C++ CCfits cfitsio 库的替代方案可能更适合您。
  3. 有库,例如Boost::GIL实现了很 multimap 像处理算法。它们在很大程度上基于模板,并提供完整的功能和良好的学习 Material 。

关于C++图像数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com