【问题标题】:C++ opencv method is slower than pythonC++ opencv方法比python慢
【发布时间】:2021-10-31 19:33:14
【问题描述】:

尝试在 c++ 中使用 opencv。 C++ 函数 cvtColor 的工作速度比在 python 上慢 16 倍。 我创建了 c++ 和 python 程序来测试 cvtColor 函数的效率。 cvtcolor 在 python 和 c++ 上返回相同的值。 Python 循环每秒运行 650-750 次。 C++ 做 25-35 次。如何解决? 我已经为 c++ 尝试过 opencv 4.5.3 和 4.2.0。

蟒蛇:

frame = cv2.imread(path)
fps = 0
clock = time.perf_counter()
while clock + 10 > time.perf_counter():
    fps += 1/10
    res = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
print(fps)

c++:

Mat frame, frame_HSV;
frame = imread(path);
frame_HSV = frame.clone();
int fps = 0;
unsigned __int64 clock_ = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
unsigned __int64 now;
clock_t start, end;
while (true) {
    fps += 1;
    now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    if (now - clock_ > 1000) {
        clock_ = now;
        cout << fps << endl;
        fps = 0;
    }
    cvtColor(frame, frame_HSV, COLOR_BGR2HSV);
}

【问题讨论】:

  • 你是否通过包管理器安装了opencv python并自己编译了opencv c++?
  • 不要在循环内打印。你测量的不是同一件事。
  • 您需要提供一个“最小可重现示例”,其中包括图片文件。此外,您正在比较不同版本的 OpenCV(4.2 和 4.5)。
  • 编译标志(主要用于 OpenCV)也很重要。如果一个版本并行运行或使用 GPU 而不是另一个版本,那么在性能上有巨大差异是完全合法的。检查资源使用情况比较两者,发现这样的问题。
  • 1) 不,我没有自己编译。 2)我每秒打印 fps,而不是 C++ 代码中的每次迭代。 3) 我在 python 中使用 4.4.0.44 opencv 并为 c++ 尝试了 4.2.0 和 4.5.3。

标签: python c++ performance opencv


【解决方案1】:

您的方法存在一些问题。我无法正确指出,但我正在展示我是如何做到的以及我的结果。

Python

(版本:4.5.1,IDE:VS Code)

import cv2
import time as t

img = cv2.imread("18JE0646.jpg")
t1 = t.time()

for _ in range(10000):
    hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

t2 = t.time()
print(t2-t1)

输出:10.5 秒

C++

(版本:4.5.2,IDE:Visual Studio 2019(发布模式))

#include <iostream>
#include <ctime>
#include <opencv2/opencv.hpp>

using namespace std;

int main() 
{
    cv::Mat img, hsvImg;
    img = cv::imread("18JE0646.jpg");
    time_t start, finish;
    
    time(&start);
    for (int i = 0 ; i < 10000 ; i++)
        cv::cvtColor(img, hsvImg, cv::COLOR_BGR2HSV);
    time(&finish);
    cout << difftime(finish, start) << " sec";
    return 0;
}

输出:4.4 秒

注意:

在 C++ 中,在运行代码之前检查模式(调试/发布),尤其是在计算算法所花费的时间时。 Debug 模式比 Release 模式慢大约 40-50 倍。 上面的 C++ 代码在 Release 模式下耗时 4.4 秒,在 Debug 模式下耗时 237 秒。

【讨论】:

  • 感谢您提供此示例。它再次证明出了点问题。我的结果:python - 13 秒,c++ - 322 秒。
  • @MrIce 阅读我刚刚在答案中添加的注释。这可能是问题所在。
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2018-06-08
  • 2011-11-23
相关资源
最近更新 更多