0

This feels like a really easy question, but I have not been able to find the answer to it.

I have a function which reads a (binary) file and feeds the content into an openCV image. Currently the file is always of the "unsigned char" datatype but I would like to expand the support to other datatypes. Preferable as an argument to the function.

I'm not very experienced with C++ but after googling around this feels like something which should be done with templates, but I am really unsure how to implement it.

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;
}
Markus
  • 2,526
  • 4
  • 28
  • 35

1 Answers1

1

cv::Mat is not a template class. You can construct a different cv::Mat simply by supplying a different type parameter to the constructor (currently hardcoded as CV_64F).

Like this:

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);
rustyx
  • 80,671
  • 25
  • 200
  • 267
  • `CV_64S` doesn't exists. You can put `CV_32S` for example. Also this doesn't take into account images with more than 1 channels, but this is OP's fault. – Miki Feb 07 '17 at 14:07