Stack is leading to segmentation fault

Hello! I am trying to create a 4d tensor out of a vector of 3d tensors, and am calling stack repeatedly. However, this is causing a segmentation fault, and Im not sure why. The size of the tensors shouldnt be the issue as stack works with torch::randn() of same dimensions.

         imageAndClass firstElem = images[0]; 
         imageAndClass secondElem = images[1]; 
         torch::Tensor training_data = firstElem.image; 
         cout << "test" << endl; 
         torch::Tensor test = torch::stack({training_data, secondElem.image}, 0); 
         cout << "test" << endl;

Where images is a std::vector of structs containing a torch::Tensor, and an integer classification.

Could you explain a bit, how you are calling torch::stack repeatedly? Are you calling it on the same tensor (training_data) or on different tensors?
Is the segfault raised in the first call or later?

After a little more debugging, I’ve realized the error is occurring earlier, when I am creating my tensor.

` torch::Tensor imgToTensor(std::string img_path) {

      cv::Mat origImage;
      cv::Mat sizedImage(200, 500, CV_32FC3);
      origImage = cv::imread(img_path, 1);
      cv::resize(origImage, sizedImage, sizedImage.size(), 0, 0, cv::INTER_LINEAR);
      cout << "test" << endl;
      torch::Tensor input = torch::from_blob(sizedImage.data, 
      {1, sizedImage.rows, sizedImage.cols, 3});
      cout << input << endl;
      input = torch::transpose(input, 1, 3);
      input = torch::transpose(input, 2, 3);
      return input;

}`

A segmentation fault is thrown after test, when i try to print/access input in any type of way.

Try this:

/*cv::CV_8UC3*/
assert(
    sizedImage.type() == 16
);

torch::Tensor input = torch::from_blob(
    sizedImage.data,
    {1, sizedImage.rows, sizedImage.cols, 3},
    torch::kByte
);

Thank you for the suggestion. I actually resolved it, and the bug is as you expected due to the type of the image not being correct. I needed to add this statement before I did the resize operation:

origImage.convertTo(origImage, CV_32FC3, 1/255.0);