c++ - uint8_t 转换 (cpp) 上的分段错误
问题描述
我这几天一直在面对这个问题!
我必须用这种结构实现一个接口来存储图像:
typedef struct Image
{
uint16_t image_width;
uint16_t image_height;
uint16_t image_depth;
uint8_t data;
Label description;
} Image;
在我的 c++ 函数中,我需要 cv::Mat 类型的图像。所以我必须将 uint8_t 类型转换为 uchar 类型(因为 cv::Mat 以 uchar 类型存储数据),反之亦然。我尝试了很多方法,但是每次我尝试在转换后以任何方式访问 Mat 图像时,都会出现分段错误。
看我的代码:
Image face;
Mat input;
Mat output;
input = imread( argv[i], 1 );
/*data = static_cast<uint8_t>(reinterpret_cast<uchar>(*input.data));
this is an alternative way found online,
but it gives the same result.
So I replaced it with the following line*/
uint8_t data = *input.data;
image_width = input.cols;
image_height = input.rows;
image_depth = input.channels();
face.data = data;
face.image_depth = image_depth;
face.image_height = image_height;
face.image_width = image_width;
output = Mat(face.image_height, face.image_width, CV_8UC3);
output.data = &face.data;
//both the following gives segmentation fault
imshow("Face", output);
cout << output << endl; //it starts printing the matrix, but it stops after a while with the seg fault
//but the following, the Mat before the convertion, does not
imshow("Face", input);
编辑。我需要做的是实现接口
using Multiface = std::vector<Image>;
class Interface {
public:
Interface();
virtual ReturnStatus createTemplate(
const Multiface &faces,
TemplateRole role,
std::vector<uint8_t> &templ,
std::vector<EyePair> &eyeCoordinates,
std::vector<double> &quality)
};
因此,在通过 imread 读取图像后,我需要将其传递给 Image 类型的向量中的 createTemplate,然后在 createTemplate 内部从中创建一个 Mat 对象。我写了前面的代码来检查是否可以转换。
问题是具有与 Image 结构相同的图片和与 Mat 相同的广告,在它们之间进行一种转换。
解决方案
cv::Mat::data
是一个指针。它指向数据的第一个元素。
通过使用*input.data
,您可以获得指针指向的内容,即数据的第一个元素。它等于input.data[0]
。
所以在赋值之后data = *input.data
,变量data
只包含第一个数据元素的值,它并不指向实际数据。因此,当您以后在某个地方完全错误face.data = data
地face.data
“指出”时。
如果您还想face.data
指向实际数据,为什么不简单地做
face.data = input.data;
face.image_depth = input.channels();
face.image_height = input.rows;
face.image_width = input.cols;
此外,&face.data
是一个指向指针的指针。你应该使用普通的output.data = face.data;