Raw read fails

asked 2014-04-22 13:39:43 -0500

black gravatar image

updated 2014-05-03 12:40:27 -0500

Hello,

When you need to read an image from disk, you go for imread. Nevertheless, I need to istantiate a Mat using raw data. Consider this code:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <fstream>
#include <memory>
#include <string>

int main()
{
 std::string path;
 std::cout << "Path: ";
 std::getline(std::cin, path);

 std::ifstream file(path, std::ifstream::binary); // raw data
 if (!file.is_open())
 {
   std::cout << "Could not open file." << std::endl;
  return 1;
 }

  file.seekg(0, file.end);
   auto fileSize = file.tellg();
  file.seekg(0, file.beg);

  std::cout << fileSize << "." << std::endl;

  std::unique_ptr<unsigned char> bufferPtr(new unsigned char[fileSize]);
 file.read(reinterpret_cast<char *>(bufferPtr.get()), fileSize);

 if (!file)
  {
    std::cout << "Could not read all data." << std::endl;
   return 1;
  }

 std::cout << "Enter file width: "; //how can I figure this
 int width;
 std::cin >> width;

 std::cout << "Enter file height: "; // and this out?
 int height;
 std::cin >> height;

 std::vector<unsigned char> buffer( bufferPtr.get(), bufferPtr.get() + fileSize);

 cv::Mat img(height, width, CV_8UC3, buffer.data());
 // as well as              ^^^^^^^ this ?
 if (img.empty())
 {
   std::cerr << "Could not load Mat object." << std::endl;
  return 1;
 }

 cv::namedWindow("window", CV_WINDOW_AUTOSIZE);
 cv::imshow("window", img);

 cv::waitKey(0);
 return 0;
}

It works most of the times indefinitely: sometimes it crashes (SIGSEGV when converting the format), sometimes shows wrong stuff.
Where am I wrong? How can I get stuff like width, height and the format as imread does?

edit retag flag offensive close merge delete

Comments

Am I forgetting any point?

black gravatar imageblack ( 2014-04-30 10:15:16 -0500 )edit

When I read raw images, the height and width was given. I'm not sure you can get properties like width, height etc straight from the raw image.

GilLevi gravatar imageGilLevi ( 2014-05-03 14:19:24 -0500 )edit