c++ - 使用 Tensorflow Lite C,数字分类器
问题描述
在 Android 上使用 Tensorflow Lite,
图像分类成功。
示例:https ://github.com/tensorflow/examples/tree/master/lite/codelabs/digit_classifier
我想将此项目转换为 C。
图像(.jpg)将使用 opencv 读取。
模型文件是 (.tflite)
给我一些建议。
这是我的程序代码。
#include <iostream>
#include <iomanip>
#include <fstream>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
#include "opencv2/opencv.hpp"
using namespace std;
typedef cv::Point3_<float> Pixel;
const uint WIDTH = 28;
const uint HEIGHT = 28;
const uint CHANNEL = 3;
const uint OUTDIM = 10;
void normalize(Pixel &pixel){
pixel.x = (pixel.x / 255.0);
pixel.y = (pixel.y / 255.0);
pixel.z = (pixel.z / 255.0);
}
int main(){
std::vector<std::string> labels;
auto file_name="labels.txt";
std::ifstream input( file_name );
for( std::string line; getline( input, line ); )
{
labels.push_back( line);
}
// read image file
cv::Mat img = cv::imread("sample2.jpg");
cv::Mat inputImg;
img.convertTo(inputImg, CV_32FC3);
cv::cvtColor(inputImg, inputImg, cv::COLOR_BGR2RGB);
// normalize to -1 & 1
Pixel* pixel = inputImg.ptr<Pixel>(0,0);
const Pixel* endPixel = pixel + inputImg.cols * inputImg.rows;
for (; pixel != endPixel; pixel++)
normalize(*pixel);
// resize image as model input
cv::resize(inputImg, inputImg, cv::Size(WIDTH, HEIGHT));
// create model
std::unique_ptr<tflite::FlatBufferModel> model =
tflite::FlatBufferModel::BuildFromFile("mnist.tflite");
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model.get(), resolver)(&interpreter);
interpreter->AllocateTensors();
float* inputLayer = interpreter->typed_input_tensor<float>(0);
float* inputImg_ptr = inputImg.ptr<float>(0);
memcpy(inputLayer, inputImg.ptr<float>(0),
WIDTH * HEIGHT * CHANNEL * sizeof(float));
interpreter->Invoke();
float* outputLayer = interpreter->typed_output_tensor<float>(0);
// TODO
return 0;
}
这个问题的总结:Android -> C Convert
我想要的结果
预测结果:6
置信度:0~1
解决方案
推荐阅读
- java - 为什么这个程序给出“除以零”错误?
- python - 大熊猫 groupby 的总和
- hazelcast - 设置 Hazelcast 集群成员的属性
- sql - Oracle 中 MS SQL 表的 sys.allocation_units 替代表是什么?
- react-native - 如何修复在本机反应中呈现平面列表?
- django - Django:为什么通过社交身份验证登录后关联了错误的用户?
- azure - 发送到 Azure Blob 容器时内容类型被覆盖
- tensorflow - 我转换后的 tensorflow 迁移学习模型总是在 Tensorflow JS 中返回相同的结果
- django - NGINX 过滤对局域网 IP 的请求
- javascript - 根据 CSS 测量文本宽度而不渲染它