C++ OpenCV方法比Python慢

2024-06-28 15:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试用C++编写OpenCV。C++函数CVTHOLD比Python慢16倍。 我创建了C++和Python程序来测试CVTHORKE函数的效率。 CVTHOLL S在Python和C++上返回相同的值。Python循环每秒运行650-750次。C++做25-35次。如何修复它? 我已经尝试了opencv4.5.3和4.2.0的C++。p>

python:

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);
}

Tags: path函数timecountercv2hsvframenow
1条回答
网友
1楼 · 发布于 2024-06-28 15:41:57

你的方法有些问题。我不能正确地指出这一点,但我正在展示我是如何做到的以及我的结果

Python

(版本:4.5.1,IDE:VS代码)

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++中,在运行代码之前检查模式(调试/发布),特别是在计算算法所花费的时间的情况下。调试模式比发布模式慢约40-50倍。 上面的C++代码在发布模式下使用了4.4秒,调试模式下使用了237秒。p>

相关问题 更多 >