我试图将cv::Mat
转换为Tensor
,所以我构建了一个函数,它显示了问题:“。exe触发了断点”,并且在调试时我发现析构函数~my_buffer()
和基类~TensorBuffer()
可能不正确。它显示了一个名为ref_.load() = 2
的函数。以下是my_buffer
类。
命令行输出:
Check failed: ref_.load() == 0 (2 vs. 0)
class my_buffer : public TensorBuffer {
public:
float * data_;
size_t len_;
~my_buffer() override {
//nothing to do
}
void* data() const override { return data_; }
size_t size() const override { return len_; }
bool OwnsMemory() const override { return false; }
TensorBuffer* root_buffer() override { return this; }
void FillAllocationDescription(AllocationDescription* proto) const override {
tensorflow::int64 rb = size();
proto->set_requested_bytes(rb);
proto->set_allocator_name(tensorflow::cpu_allocator()->Name());
}
以防万一,其余代码:
Tensor cv2tensor(const cv::Mat & img )
{
int height = 1069;
int width = 500;
int chanel = 3;
int bacth = 1;
int input_size = height*width*chanel;
std::vector<float> input_buffer(input_size);
/*float * input_data = input_buffer.data();*/
const int64_t dim[4] = { bacth, width, height, chanel };
my_buffer tensor_buf;
//////////////////////////////////////////////////////
/*img.reshape(1);*/
int count = 0;
/*for (int i=0;i<)*/
for (int i = 0; i < 3; i++)
{
for (int row = 0; row < img.rows; row++)
{
for (int col = 0; col < img.cols; col++)
{
input_buffer[count] = img.at<cv::Vec3b>(row, col)[0];
count += 1;
}
}
}
////////////////////////////////////////////////////////
tensor_buf.data_ = (float *)input_buffer.data();
tensor_buf.len_ = input_size;
std::vector<tensorflow::int64> tensor_dim;
for (int i = 0; i < 4; i++)
tensor_dim.push_back(dim[i]);
Tensor input_tensor = tensorflow::TensorCApi::create_tensor(DT_FLOAT, TensorShape(tensor_dim), &tensor_buf);
//cv::resize()
/*Tensor input_tensor;*/
return input_tensor;
}
答案 0 :(得分:0)
将OpenCV矩阵转换为张量实际上更直接(从here):
// just for this answer:
using namespace tensorflow;
cv::Mat image;
cv::Mat image_float;
image.convertTo(image_float, CV_32FC3);
float *image_float_data = (float*)image_float.data;
TensorShape my_shape = TensorShape{1, image.rows, image.cols, image.channels()};
Tensor my_tensor = Tensor(DT_FLOAT, my_shape);
std::copy_n((char*) image_float_data,
my_shape.num_elements() * sizeof(float),
const_cast<char*>(my_tensor.tensor_data().data()));
您为什么要迭代数据? 为什么要创建自己的缓冲区类?