serizba / cppflow

Run TensorFlow models in C++ without installation and without Bazel

Home Page:https://serizba.github.io/cppflow/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to threshold a tensor to generate a binary image

bmiftah opened this issue · comments

Hi , I am working on segmenation problem. The model was trained and succecssfully loaded to C++ using the method suggested. I was tring to threshold my model output to generate a binary image . I want to threshold the pixles to certain value and make all pixles either 1 or 0 (binary white and black image) based on the thresholding value. here is what I tried based on my search : -

cppflow::model model("model");
auto output_tensor = model_abdomen(input);
output_tensor = tf.where(output_tensor >0.5, 1, 0) -- this is in fact from tenforflow APIs I don't know if this is supported in cppflow.

model is the name of my model, it returns predicted tensor-output
Cany anyone help me to share how to use "output_tensor = tf.where(output_tensor >0.5, 1, 0)" from cppflow Library ,I try it this way ;-

auto output_tensor = cppflow::where(output_tensor >0.5, 1, 0)

but it gave me the following error
note: template argument deduction/substitution failed:
AC.cpp:44:56: note: ‘cppflow::tensor’ is not derived from ‘const std::multiset<_Key, _Compare, _Allocator>’
44 | auto output_tensor = cppflow::where(output_tensor >0.5, 1, 0)

one more thing ... Is there a function to change tensorf to image in c++ using the cppflow interface ...

Thank you so much in advance

Hi @bmiftah

For such operation you can do a comparison and a cast:

auto binary_tensor = cppflow::cast(cppflow::greater(output_tensor, 0.5f), TF_BOOL, TF_FLOAT);

First you perform a greater than operation that transforms the input tensor into a tensor of booleans, and then convert those booleans to floats (false will be 0s and true will be 1s)

Thank you so much @serizba . Casting and greater than funtion worked for me. I was aksing at the bottom of my previous question if there is cppflow routine to convert tensor to image , Or should I change the binary_tensor to c++ MAT/VECTOR and save it as image ? I will close this issue after this follow up. thanks

What do you mean to convert to an image? To a cv::Mat? Or to save it to disk?

Yes , that is what I meant, tensor to cv::Mat and later to save it as image with imwrite(). Thanks

For cv::Mat you will need to first get the tensor data with tensor::get_data() and then create a mat from there. There isn't yet a direct method to convert from one to the other.

Yes, I did vector output = tensor.get_data(); which return vector data . I will proceed from here to Mat , may be with nested for-loop . Thank you @serizba