samples/dnn/segmentation.cpp#

  1#include <fstream>
  2#include <sstream>
  3#include <iostream>
  4
  5#include <opencv2/dnn.hpp>
  6#include <opencv2/imgproc.hpp>
  7#include <opencv2/highgui.hpp>
  8#include <opencv2/core/utils/logger.hpp>
  9
 10#include "common.hpp"
 11
 12using namespace cv;
 13using namespace std;
 14using namespace dnn;
 15
 16const string about =
 17        "Use this script to run semantic segmentation deep learning networks using OpenCV.\n\n"
 18        "Firstly, download required models using `download_models.py` (if not already done). Set environment variable OPENCV_DOWNLOAD_CACHE_DIR to specify where models should be downloaded. Also, point OPENCV_SAMPLES_DATA_PATH to opencv/samples/data.\n"
 19        "To run:\n"
 20        "\t ./example_dnn_classification modelName(e.g. u2netp) --input=$OPENCV_SAMPLES_DATA_PATH/butterfly.jpg (or ignore this argument to use device camera)\n"
 21        "Model path can also be specified using --model argument.";
 22
 23const string param_keys =
 24    "{ help  h    |                   | Print help message. }"
 25    "{ @alias     |                   | An alias name of model to extract preprocessing parameters from models.yml file. }"
 26    "{ zoo        | ../dnn/models.yml | An optional path to file with preprocessing parameters }"
 27    "{ device     |         0         | camera device number. }"
 28    "{ input i    |                   | Path to input image or video file. Skip this argument to capture frames from a camera. }"
 29    "{ colors     |                   | Optional path to a text file with colors for an every class. "
 30    "Every color is represented with three values from 0 to 255 in BGR channels order. }";
 31
 32const string backend_keys = format(
 33    "{ backend          | default | Choose one of computation backends: "
 34                              "default: automatically (by default), "
 35                              "openvino: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
 36                              "opencv: OpenCV implementation, "
 37                              "vkcom: VKCOM, "
 38                              "cuda: CUDA, "
 39                              "webnn: WebNN }");
 40
 41const string target_keys = format(
 42    "{ target           | cpu | Choose one of target computation devices: "
 43                              "cpu: CPU target (by default), "
 44                              "opencl: OpenCL, "
 45                              "opencl_fp16: OpenCL fp16 (half-float precision), "
 46                              "vpu: VPU, "
 47                              "vulkan: Vulkan, "
 48                              "cuda: CUDA, "
 49                              "cuda_fp16: CUDA fp16 (half-float preprocess) }");
 50
 51string keys = param_keys + backend_keys + target_keys;
 52vector<string> labels;
 53vector<Vec3b> colors;
 54
 55
 56static void colorizeSegmentation(const Mat &score, Mat &segm)
 57{
 58    const int rows = score.size[2];
 59    const int cols = score.size[3];
 60    const int chns = score.size[1];
 61
 62    if (colors.empty())
 63    {
 64        // Generate colors.
 65        colors.push_back(Vec3b());
 66        for (int i = 1; i < chns; ++i)
 67        {
 68            Vec3b color;
 69            for (int j = 0; j < 3; ++j)
 70                color[j] = (colors[i - 1][j] + rand() % 256) / 2;
 71            colors.push_back(color);
 72        }
 73    }
 74    else if (chns != (int)colors.size())
 75    {
 76        CV_Error(Error::StsError, format("Number of output labels does not match "
 77                                         "number of colors (%d != %zu)",
 78                                         chns, colors.size()));
 79    }
 80
 81    Mat maxCl = Mat::zeros(rows, cols, CV_8UC1);
 82    Mat maxVal(rows, cols, CV_32FC1, score.data);
 83    for (int ch = 1; ch < chns; ch++)
 84    {
 85        for (int row = 0; row < rows; row++)
 86        {
 87            const float *ptrScore = score.ptr<float>(0, ch, row);
 88            uint8_t *ptrMaxCl = maxCl.ptr<uint8_t>(row);
 89            float *ptrMaxVal = maxVal.ptr<float>(row);
 90            for (int col = 0; col < cols; col++)
 91            {
 92                if (ptrScore[col] > ptrMaxVal[col])
 93                {
 94                    ptrMaxVal[col] = ptrScore[col];
 95                    ptrMaxCl[col] = (uchar)ch;
 96                }
 97            }
 98        }
 99    }
100    segm.create(rows, cols, CV_8UC3);
101    for (int row = 0; row < rows; row++)
102    {
103        const uchar *ptrMaxCl = maxCl.ptr<uchar>(row);
104        Vec3b *ptrSegm = segm.ptr<Vec3b>(row);
105        for (int col = 0; col < cols; col++)
106        {
107            ptrSegm[col] = colors[ptrMaxCl[col]];
108        }
109    }
110}
111
112static void showLegend(FontFace fontFace)
113{
114    static const int kBlockHeight = 30;
115    static Mat legend;
116    if (legend.empty())
117    {
118        const int numClasses = (int)labels.size();
119        if ((int)colors.size() != numClasses)
120        {
121            CV_Error(Error::StsError, format("Number of output labels does not match "
122                                             "number of labels (%zu != %zu)",
123                                             colors.size(), labels.size()));
124        }
125        legend.create(kBlockHeight * numClasses, 200, CV_8UC3);
126        for (int i = 0; i < numClasses; i++)
127        {
128            Mat block = legend.rowRange(i * kBlockHeight, (i + 1) * kBlockHeight);
129            block.setTo(colors[i]);
130            Rect r = getTextSize(Size(), labels[i], Point(), fontFace, 15, 400);
131            r.height += 15; // padding
132            r.width += 10; // padding
133            rectangle(block, r, Scalar::all(255), FILLED);
134            putText(block, labels[i], Point(10, kBlockHeight/2), Scalar(0,0,0), fontFace, 15, 400);
135        }
136        namedWindow("Legend", WINDOW_AUTOSIZE);
137        imshow("Legend", legend);
138    }
139}
140
141int main(int argc, char **argv)
142{
143    utils::logging::setLogLevel(utils::logging::LOG_LEVEL_INFO);
144
145    CommandLineParser parser(argc, argv, keys);
146
147    const string modelName = parser.get<String>("@alias");
148    const string zooFile = findFile(parser.get<String>("zoo"));
149
150    keys += genPreprocArguments(modelName, zooFile);
151
152    parser = CommandLineParser(argc, argv, keys);
153    parser.about(about);
154    if (!parser.has("@alias") || parser.has("help"))
155    {
156        parser.printMessage();
157        return 0;
158    }
159
160    string sha1 = parser.get<String>("sha1");
161    float scale = parser.get<float>("scale");
162    Scalar mean = parser.get<Scalar>("mean");
163    bool swapRB = parser.get<bool>("rgb");
164    int inpWidth = parser.get<int>("width");
165    int inpHeight = parser.get<int>("height");
166    String model = findModel(parser.get<String>("model"), sha1);
167    const string backend = parser.get<String>("backend");
168    const string target = parser.get<String>("target");
169    int stdSize = 20;
170    int stdWeight = 400;
171    int stdImgSize = 512;
172    int imgWidth = -1; // Initialization
173    int fontSize = 50;
174    int fontWeight = 500;
175    FontFace fontFace("sans");
176
177    // Open file with labels names.
178    if (parser.has("labels"))
179    {
180        string file = findFile(parser.get<String>("labels"));
181        ifstream ifs(file.c_str());
182        if (!ifs.is_open())
183            CV_Error(Error::StsError, "File " + file + " not found");
184        string line;
185        while (getline(ifs, line))
186        {
187            labels.push_back(line);
188        }
189    }
190    // Open file with colors.
191    if (parser.has("colors"))
192    {
193        string file = findFile(parser.get<String>("colors"));
194        ifstream ifs(file.c_str());
195        if (!ifs.is_open())
196            CV_Error(Error::StsError, "File " + file + " not found");
197        string line;
198        while (getline(ifs, line))
199        {
200            istringstream colorStr(line.c_str());
201
202            Vec3b color;
203            for (int i = 0; i < 3 && !colorStr.eof(); ++i)
204                colorStr >> color[i];
205            colors.push_back(color);
206        }
207    }
208
209    if (!parser.check())
210    {
211        parser.printErrors();
212        return 1;
213    }
214
215    CV_Assert(!model.empty());
216    //! [Read and initialize network]
217    EngineType engine = ENGINE_AUTO;
218    if (backend != "default" || target != "cpu"){
219        engine = ENGINE_CLASSIC;
220    }
221    Net net = readNetFromONNX(model, engine);
222    net.setPreferableBackend(getBackendID(backend));
223    net.setPreferableTarget(getTargetID(target));
224    net.setProfilingMode(DNN_PROFILE_SUMMARY);
225     //! [Read and initialize network]
226    // Create a window
227    static const string kWinName = "Deep learning semantic segmentation in OpenCV";
228    namedWindow(kWinName, WINDOW_AUTOSIZE);
229
230    //! [Open a video file or an image file or a camera stream]
231    VideoCapture cap;
232    if (parser.has("input"))
233        cap.open(findFile(parser.get<String>("input")));
234    else
235        cap.open(parser.get<int>("device"));
236
237    if (!cap.isOpened()) {
238        cerr << "Error: Video could not be opened." << endl;
239        return -1;
240    }
241
242    //! [Open a video file or an image file or a camera stream]
243    // Process frames.
244    Mat frame, blob;
245    while (waitKey(1) < 0)
246    {
247        cap >> frame;
248        if (frame.empty())
249        {
250            waitKey();
251            break;
252        }
253        if (imgWidth == -1){
254            imgWidth = max(frame.rows, frame.cols);
255            fontSize = min(fontSize, (stdSize*imgWidth)/stdImgSize);
256            fontWeight = min(fontWeight, (stdWeight*imgWidth)/stdImgSize);
257        }
258        imshow("Original Image", frame);
259        //! [Create a 4D blob from a frame]
260        blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, false);
261        //! [Set input blob]
262        net.setInput(blob);
263        //! [Set input blob]
264        int64 t0 = getTickCount();
265
266        if (modelName == "u2netp")
267        {
268            vector<Mat> output;
269            net.forward(output, net.getUnconnectedOutLayersNames());
270            net.printPerfProfile();
271
272            Mat pred = output[0].reshape(1, output[0].size[2]);
273            pred.convertTo(pred, CV_8U, 255.0);
274            Mat mask;
275            resize(pred, mask, Size(frame.cols, frame.rows), 0, 0, INTER_AREA);
276
277            // Create overlays for foreground and background
278            Mat foreground_overlay;
279
280            // Set foreground (object) to red
281            Mat all_zeros = Mat::zeros(frame.size(), CV_8UC1);
282            vector<Mat> channels = {all_zeros, all_zeros, mask};
283            merge(channels, foreground_overlay);
284
285            // Blend the overlays with the original frame
286            addWeighted(frame, 0.25, foreground_overlay, 0.75, 0, frame);
287        }
288        else
289        {
290            //! [Make forward pass]
291            Mat score = net.forward();
292            net.printPerfProfile();
293            //! [Make forward pass]
294            Mat segm;
295            colorizeSegmentation(score, segm);
296            resize(segm, segm, frame.size(), 0, 0, INTER_NEAREST);
297            addWeighted(frame, 0.1, segm, 0.9, 0.0, frame);
298        }
299
300        // Put efficiency information.
301        double t = (getTickCount() - t0) * 1000.0 / getTickFrequency();
302        string label = format("Inference time: %.2f ms", t);
303        Rect r = getTextSize(Size(), label, Point(), fontFace, fontSize, fontWeight);
304        r.height += fontSize; // padding
305        r.width += 10; // padding
306        rectangle(frame, r, Scalar::all(255), FILLED);
307        putText(frame, label, Point(10, fontSize), Scalar(0,0,0), fontFace, fontSize, fontWeight);
308
309        imshow(kWinName, frame);
310        if (!labels.empty())
311            showLegend(fontFace);
312    }
313    return 0;
314}