簡體   English   中英

C++ 比 opencv 中的 python 慢很多

[英]C++ is quite slower than python in opencv

startTime = time.time()
blob = cv2.dnn.blobFromImage(img, float(1.0/255.0), (frameWidth,frameHeight), (0,0,0), swapRB = True, crop = False)
yolo.setInput(blob)
layerOutput = yolo.forward(outputLayers)
endTime = time.time()

Python 代碼,我正在測量時間

auto start = chrono::steady_clock::now();
blob = blobFromImage(images[i], 1.0f/255.0f, Size(frameWidth, frameHeight), Scalar(0,0,0), true, false);
net.setInput(blob);
net.forward(layerOutput, getOutputsNames(net));
auto end = chrono::steady_clock::now();

我正在測量時間的 C++ 代碼

在 C++ 中:

blob 是Mat類型,layerOutput 是vector<Mat>類型, getOutputsNamesvector<string>名稱返回。

在 python 中:blob 是numpy.ndarray類型, layerOutputtuple類型, outputLayerslist類型 object。

后端和目標都是一樣的,后端是opencv,目標是cpu,我在同一個目錄中使用相同的yolov4權重和配置文件

測量時間時,在 python 中大約需要 180-200 毫秒,而在 C++ 中大約需要 220-250 毫秒。 由於 C++ 是一種編譯語言,我預計 C++ 的工作速度會比 python 快得多,但事實並非如此。

python 比 C++ 工作得更快的原因可能是什么? 另外,您對此有什么解決方案?

提前致謝!

首先,它不是那樣的。 python-opencv模塊多用 C++ 和 C 編寫。 然后 python 可能會使用某種綁定來使用編譯后的代碼。 比如我在C++中寫了一個圖片注冊碼,用pybind從python調用二進制(.so文件)。 所以如果它工作得更快,它不僅僅是 Python。 現在來回答你的問題。 您的 python 代碼比 C++ 運行得更快可能有多種原因。

  1. 正如在評論中,有人提到這可能是因為 Opencv 模塊為 Python 使用了優化的二進制文件。

  2. 在運行這兩個代碼時檢查 CPU 利用率和線程數。

  3. 它可能是導致速度的數據結構和算法。 Example, you are using Mat to read the image in C++ while for Python you are using Numpy which have it's core written in C which is faster than C++.

I figured what the problem is, I have customized OpenCV for c++ to gain advantage of the CUDA cores in my Jetson Orin, yet the python uses general OpenCV stored in other directory, which doesn't have CUDA support. 當我將 C++ 的 OpenCV 編譯更改為通用編譯時,它按預期運行得很快,因為在我的自定義編譯中,我還自定義了 CPU 並行化,這似乎比默認的慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM