这感觉就像一个非常简单的问题,但我找不到答案。
我有一个函数,它读取(二进制)文件并将内容提供给openCV图像。目前该文件始终是" unsigned char"数据类型,但我想扩展对其他数据类型的支持。最好作为函数的参数。
我对C ++不是很有经验,但在谷歌搜索后感觉就像应该用模板做的事情,但我真的不确定如何实现它。
cv::Mat ReadImage(const char * filename, int dataTypeSize, int imageWidth)
{
auto read_image = fopen(filename, "rb");
if (read_image == nullptr)
{
printf("Image Not Found\n");
return cv::Mat();
}
fseek(read_image, 0, SEEK_END);
int fileLen = ftell(read_image);
fseek(read_image, 0, SEEK_SET);
auto pre_image = static_cast<unsigned char *>(malloc(fileLen));
auto data = fread(pre_image, 1, fileLen, read_image);
// Printed and verify the values
//printf("File Size %d\n", fileLen);
//printf("Read bytes %zd\n", data);
auto width = imageWidth;
auto height = fileLen / dataTypeSize / imageWidth;
fclose(read_image);
vector<unsigned char> buffer(pre_image, pre_image + data);
auto img = cv::Mat(height, width, CV_64F, pre_image);
//printf("Image rows %d\n", img.rows);
//printf("Image cols %d\n", img.cols);
return img;
}
答案 0 :(得分:1)
cv::Mat
不是模板类。您只需向构造函数提供不同的cv::Mat
参数(目前硬编码为type
)即可构建不同的CV_64F
。
像这样:
cv::Mat ReadImage(const char * filename, int dataTypeSize, int imageWidth, int type)
{
. . .
auto img = cv::Mat(height, width, type, pre_image);
return img;
}
auto mat = ReadImage("abc", 8, 1000, CV_32S);