首页 > 解决方案 > C++ 运行时间正在增加

问题描述

我已经使用 CNTK 制作了一个图像评估器。我在一个循环中加载了模型并评估了 4000 张图像并迭代了几次。

然而,这个程序的运行时间随着重复循环而增加。我已经使用 std::clock() 检查了每个运行时间。然后,将 Mat 转换为矢量和相反函数的图像处理函数会越来越多地使用时间。我检查了输入和输出变量的大小,但它们没有改变。此外,图像处理函数所在的类中没有成员变量。所以我很好奇这段代码是否会导致这个问题。

这些是转换功能。

Mat ImageProcessing::getMatFromData(const NDShape imageDims, const vector<float> & data, double min, double max, bool inversechannel)
{
    auto maxval = max < 0 ? (double)(*max_element(data.begin(), data.end())) : max;
    auto minval = min < 0 ? (double)(*min_element(data.begin(), data.end())) : min;

    if (maxval == minval)
    {
        minval = 0;
        maxval = 1;
    }

    int offset = imageDims[0] * imageDims[1];
    auto ratio = 255.0f / (maxval - minval);

    auto vmSplit = vector<Mat>(imageDims[2], Mat(imageDims[0], imageDims[1], CV_32FC1));
    auto mat = Mat(imageDims[0], imageDims[1], CV_8U);

    try {
        uchar* output = mat.data;

        if (imageDims[2] == 1)
        {
            parallel_for(0, offset, [&](auto i)
            {
                float p = data[i];
                output[i] = (uchar)((p - minval) * ratio);
            });
        }
        else if (imageDims[2] == 3)
        {
            parallel_for(0, offset, [&](auto i)
            {
                float b = data[offset * 0 + i];
                float g = data[offset * 1 + i];
                float r = data[offset * 2 + i];
                output[i] = (uchar)((((r + g + b) / 3.0) - minval) * ratio);
            });
        }
        else
        {
            cout << "getMatFromData - channels error" << endl;
            throw;
        }
    }
    catch (exception e)
    {
    }
    return mat;
}

vector<float> ImageProcessing::getDataFromMat(vector<int> imageDims, Mat org, float weight, float bias, bool noise)
{
    auto imageHeight = org.rows;
    auto imageWidth = org.cols;
    auto offset = imageHeight * imageWidth;

    Mat mat = Mat();
    Mat matSplit[3];
    auto features = vector<float>(offset * org.channels());

    try
    {
        if (noise)
        {
            auto noise_mat = Mat(Size(org.cols, org.rows), org.type());
            randn(noise_mat, Scalar::all(0), Scalar::all(30));
            add(org, noise_mat, mat);
        }
        else
        {
            mat = org;
        }

        split(mat, matSplit);

        parallel_for(0, mat.channels(), [&](auto i)
        {
            matSplit[i].convertTo(matSplit[i], CV_32F);
            copy((float*)matSplit[i].datastart, (float*)matSplit[i].dataend, features.begin() + offset * i);
        });
    }
    catch (exception e)
    {
    }

    return features;
}

标签: c++opencv

解决方案


推荐阅读