事实证明cv::Mat
,为了成功复制,指定尺寸是必要的!也就是说,我需要这样做:
cv::Mat input_array (3, 1, CV_32FC1);
cv::Mat destination_array (3, 1, CV_32FC1);
std::memcpy(input_array.data, src.data_ptr<float>(), sizeof(float) * src.numel());
std::memcpy(destination_array.data, dst.data_ptr<float>(), sizeof(float) * dst.numel());
std::cout << input_array << std::endl;
std::cout << destination_array << std::endl;
这不再导致访问冲突。我可以验证这些值是否被复制:
[1.1;
2;
3.3]
[1.1;
2;
3.3]
由于前一个示例使用了虚构的输入数据,因此cv::getAffineTransform()
会崩溃,所以这里有一个更真实的输入和输出,您可以运行并查看它是否有效:
方法一:使用std::memcpy
复制数据:
torch::Tensor src = torch::tensor({ {137.47012, 62.52604}, {170.50703, 64.21498}, {154.49675, 80.78379} });
torch::Tensor dst = torch::tensor({ {38.294598, 51.6963}, {73.5318, 51.5014}, {56.0252, 71.7366} });
std::cout << "src.shapes: " << src.sizes() << std::endl;
std::cout << "dst.shapes: " << dst.sizes() << std::endl;
int rows = src.sizes()[0];
int cols = (src.sizes().size() == 1) ? 1 : src.sizes()[1];
cv::Mat input_array (rows, cols, CV_32FC1);
cv::Mat destination_array (rows, cols, CV_32FC1);
std::memcpy(input_array.data, src.data_ptr<float>(), sizeof(float) * src.numel());
std::memcpy(destination_array.data, dst.data_ptr<float>(), sizeof(float) * dst.numel());
std::cout << "input_array:\n" << input_array << std::endl;
std::cout << "destination_array:\n" << destination_array << std::endl;
auto tfm = cv::getAffineTransform(input_array, destination_array);
std::cout << "tfm:\n" << tfm << std::endl;
和
方法 2:使用底层缓冲区而不是复制:
int height = src.sizes()[0];
int width = src.sizes()[1];
cv::Mat input_array(cv::Size{width, height }, CV_32F, src.data_ptr<float>());
cv::Mat destination_array(cv::Size{ width, height }, CV_32F, dst.data_ptr<float>());