當前位置: 妍妍網 > 碼農

OpenCV4 C++開發築基之數據轉換

2024-03-06碼農

點選上方 藍字 關註我們

微信公眾號: OpenCV學堂

關註獲取更多電腦視覺與深度學習知識

前言

之前我寫過一篇介紹學習OpenCV C++一些前置基礎C++11的基礎知識,主要是介紹了輸出打印、各種常見數據容器。這裏又整理了一篇,主要涉及各種數據型別之間的相互轉換。用C++寫程式碼,特別是寫演算法,很多時候會遇到各種精度的數據相互轉換、顯示的時候還會遇到不同型別變量相互轉換,因此個人總結了一下,主要有以下三種常見的數據轉換

01

數據高低精度轉換

最常見的就是int型別轉float或者是float轉int,而C++語言預設的自動轉型有時候帶來意向不到的大BUG。所以最好采用顯式的強制轉型方式比較好。推薦使用 static_cast ,它是C++ 中四個命名強制型別轉換操作符之一,經常被用於基礎數據型別轉換,非常好用。

想把輸入影像 512x512 的縮放到 300x300 ,先計算縮放:

cv::Mat image = cv::imread("D:/images/lena.jpg");int w = image.cols;int h = image.rows;std::cout << " width: " << w << std::endl;std::cout << " height: " << h << std::endl;float sx = w / 300;float sy = h / 300;std::cout << " sx: " << sx << " sy: " << sy << std::endl;

執行結果如下:

必須先把w跟h強制轉型為float,程式碼修改如下:

cv::Mat image = cv::imread("D:/images/lena.jpg");float w = static_cast<float>(image.cols);float h = static_cast<float>(image.rows);std::cout << " width: " << w << std::endl;std::cout << " height: " << h << std::endl;float sx = w / 300;float sy = h / 300;std::cout << " sx: " << sx << " sy: " << sy << std::endl;

我們都知道這種情況下計算出來的縮放比例,sx跟sy應該是浮點數,但是如 果這個時候左側默寫都是int型別,直接這樣計算就導致了先會生成int型別的結果,然後再轉float,這點跟python語言語法不同,所以得到的sx跟sy都等於,執行結果如下:

這個時候計算就正確了,所以推薦基本數據型別轉換用 static_cast 顯式完成。

02

數值轉換

在OpenCV編程開發中,有時候會讀取數據檔,需要把數據從字元(string)型別轉為數值(number)型別,常見的有int、float、double、long等型別與string型別的相互轉換,這部份的轉換主要依賴函式:

  • std::to_string 這個是萬能的,我寫出了C#與Java的既視感!

  • atoi 轉化為整數int型別

  • atof 轉換為浮點數float型別

  • 程式碼演示如下:

    // 各種字元與數值轉換
    double d = 1.234;
    float f = 3.145;
    int i = 314;
    long l = 22;
    std::cout << std::to_string(d) << std::endl;
    std::cout << std::to_string(f) << std::endl;
    std::cout << std::to_string(i) << std::endl;
    std::cout << std::to_string(l) << std::endl;

    // 從string到數值
    constchar* str1 = "3.2333";
    constchar* str2 = "5.321";
    float f1 = std::atof(str1);
    float f2 = std::atof(str2);
    float f3 = f1 + f2;
    std::cout << f3 << std::endl;

    constchar* str3 = "100";
    constchar* str4 = "121";
    int i3 = std::atoi(str3) + std::atoi(str4);
    std::cout << i3 << std::endl;

    執行結果如下:

    此外各種數值型別相互轉化,主要依賴static_cast函式,使用如下:

    int a1 = 100;
    float f8 = 20;
    float sum = std::max(static_cast<float>(a1), f8);

    03

    wchar與char轉換為std::string

    網上有各種C++語言的 wchar與char如何轉換為std::string 的例子,但是我個人最喜歡或者推薦用的基於C++標準函式的介面轉換,簡單快捷有效。 wchar轉std::string 方法如下:

    // wchar轉std::stringstd::wstring wstxt(wchar_txt);std::stringstrtxt(wstxt.begin(), wstxt.end());

    char轉std::string 方法

    對於char或者其它數值型別轉換為std::string型別,推薦使用字元流物件 ostringstream ,這個簡直是太好用,程式碼如下:

    std::ostringstream ss;std::wstring wstxt(wchar_txt);std::stringstrtxt(wstxt.begin(), wstxt.end());ss << char_buff;ss << "-";ss << "your text content";ss << "-";ss << strtxt;std::cout << ss.str() << std::endl;

    總結: 數值到字串轉換記住std::tostring 與ostringstream 就萬事可成!

    系統化學習直接掃碼檢視

    推薦閱讀