ncnn

Форк
0
/
shufflenetv2.cpp 
125 строк · 3.3 Кб
1
// Tencent is pleased to support the open source community by making ncnn available.
2
//
3
// Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
4
//
5
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6
// in compliance with the License. You may obtain a copy of the License at
7
//
8
// https://opensource.org/licenses/BSD-3-Clause
9
//
10
// Unless required by applicable law or agreed to in writing, software distributed
11
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13
// specific language governing permissions and limitations under the License.
14

15
#include "net.h"
16

17
#include <algorithm>
18
#if defined(USE_NCNN_SIMPLEOCV)
19
#include "simpleocv.h"
20
#else
21
#include <opencv2/core/core.hpp>
22
#include <opencv2/highgui/highgui.hpp>
23
#endif
24
#include <stdio.h>
25
#include <vector>
26

27
static int detect_shufflenetv2(const cv::Mat& bgr, std::vector<float>& cls_scores)
28
{
29
    ncnn::Net shufflenetv2;
30

31
    shufflenetv2.opt.use_vulkan_compute = true;
32

33
    // https://github.com/miaow1988/ShuffleNet_V2_pytorch_caffe
34
    // models can be downloaded from https://github.com/miaow1988/ShuffleNet_V2_pytorch_caffe/releases
35
    if (shufflenetv2.load_param("shufflenet_v2_x0.5.param"))
36
        exit(-1);
37
    if (shufflenetv2.load_model("shufflenet_v2_x0.5.bin"))
38
        exit(-1);
39

40
    ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, 224, 224);
41

42
    const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
43
    in.substract_mean_normalize(0, norm_vals);
44

45
    ncnn::Extractor ex = shufflenetv2.create_extractor();
46

47
    ex.input("data", in);
48

49
    ncnn::Mat out;
50
    ex.extract("fc", out);
51

52
    // manually call softmax on the fc output
53
    // convert result into probability
54
    // skip if your model already has softmax operation
55
    {
56
        ncnn::Layer* softmax = ncnn::create_layer("Softmax");
57

58
        ncnn::ParamDict pd;
59
        softmax->load_param(pd);
60

61
        softmax->forward_inplace(out, shufflenetv2.opt);
62

63
        delete softmax;
64
    }
65

66
    out = out.reshape(out.w * out.h * out.c);
67

68
    cls_scores.resize(out.w);
69
    for (int j = 0; j < out.w; j++)
70
    {
71
        cls_scores[j] = out[j];
72
    }
73

74
    return 0;
75
}
76

77
static int print_topk(const std::vector<float>& cls_scores, int topk)
78
{
79
    // partial sort topk with index
80
    int size = cls_scores.size();
81
    std::vector<std::pair<float, int> > vec;
82
    vec.resize(size);
83
    for (int i = 0; i < size; i++)
84
    {
85
        vec[i] = std::make_pair(cls_scores[i], i);
86
    }
87

88
    std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
89
                      std::greater<std::pair<float, int> >());
90

91
    // print topk and score
92
    for (int i = 0; i < topk; i++)
93
    {
94
        float score = vec[i].first;
95
        int index = vec[i].second;
96
        fprintf(stderr, "%d = %f\n", index, score);
97
    }
98

99
    return 0;
100
}
101

102
int main(int argc, char** argv)
103
{
104
    if (argc != 2)
105
    {
106
        fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
107
        return -1;
108
    }
109

110
    const char* imagepath = argv[1];
111

112
    cv::Mat m = cv::imread(imagepath, 1);
113
    if (m.empty())
114
    {
115
        fprintf(stderr, "cv::imread %s failed\n", imagepath);
116
        return -1;
117
    }
118

119
    std::vector<float> cls_scores;
120
    detect_shufflenetv2(m, cls_scores);
121

122
    print_topk(cls_scores, 3);
123

124
    return 0;
125
}
126

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.