forked from tuotuoxp/cpp-torch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
56 lines (49 loc) · 1.7 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/opencv.hpp>
#include <cpptorch/cpptorch.h>
const int img_dim = 96;
int main(int argc, char** argv)
{
// 1. load 96*96 RGB image to OpenCV Mat
cv::Mat image = cv::imread("face.jpg");
if (image.channels() != 3 || image.rows != img_dim || image.cols != img_dim)
{
std::cerr << "invalid size" << image.channels() << " " << image.rows << " " << image.cols << " " << std::endl;
return 1;
}
// 2. create input tensor from CV Mat
cpptorch::Tensor<float> input;
input.create();
input.resize({1, 3, image.rows, image.cols});
const unsigned char *img = image.ptr(0);
float *ten = input.data();
for (size_t c = 0; c < 3; c++)
{
for (size_t p = 0; p < img_dim * img_dim; p++)
{
ten[c * img_dim * img_dim + p] = (float)img[p * 3 + 2 - c] / 255; // normalize to [0,1]
}
}
// 3. load openface network
std::ifstream fs_net(std::string("nn4.small2.v1.t7"), std::ios::binary);
if (!fs_net.good())
{
std::cerr << "Cannot find torch module: nn4.small2.v1.t7" << std::endl
<< "Please download from http://openface-models.storage.cmusatyalab.org/nn4.small2.v1.t7" << std::endl;
return 2;
}
auto obj_t = cpptorch::load(fs_net);
std::shared_ptr<cpptorch::nn::Layer<float>> net = cpptorch::read_net<float>(obj_t.get());
// 4. foward
cpptorch::Tensor<float> output = net->forward(input);
// 5. print 1*128 output
const float *output_ptr = output.data();
for (int i = 0; i < 128; i++)
{
std::cout << output_ptr[i] << " ";
}
std::cout << std::endl;
return 0;
}