【问题标题】:How to convert varbinary data (as string) to byte array?如何将 varbinary 数据(作为字符串)转换为字节数组?
【发布时间】:2017-02-08 08:07:18
【问题描述】:

我有一个 varbinary(BLOB) 数据作为字符串(图像数据)

例如,

std::string ByteStr = "FF-D8-E0-FF-85 ... " ;

我想将此字符串转换为字节数组(或有用的东西),然后用作cv::Mat 格式。我从另一种方法获取字符串。我尝试转换,但出现 OpenCV 错误。

我得到的错误,

OpenCV 错误:cv::imshow 中的断言失败 (size.width>0 && size.height>0),>>file ........\opencv\modules\highgui\src\window.cpp

C++ 代码,

std::string ByteStr = obj->GetBinaryStr();  // this provide varbinary string
std::vector<uchar> vct;
std::string delimiter = "-";

        size_t pos = 0;
        std::string token;

        while ((pos = ByteStr.find(delimiter)) != std::string::npos) {

            token = ByteStr.substr(0, pos);
            vct.push_back((uchar)(token.c_str()));
            ByteStr.erase(0, pos + delimiter.length());

        }          

       cv::Mat img = cv::imdecode(vct,CV_BGR2GRAY );
       cv::namedWindow("MyWindow");
       cv::imshow("MyWindow",img);

如何将此字符串转换为cv::Mat 格式。有什么建议吗?

提前致谢

【问题讨论】:

    标签: c++ image opencv blob


    【解决方案1】:

    cv::imdecode(vct,CV_BGR2GRAY ); 没有任何意义。请使用有意义的东西,例如cv::imdecode(vct, cv2.IMREAD_GRAYSCALE );

    您还需要将十六进制字符串转换为整数类型。您可以为此使用strtol

    代码变成这样:

    std::string ByteStr = obj->GetBinaryStr();  // this provide varbinary string
    std::vector<uchar> vct;
    std::string delimiter = "-";
    
    size_t pos = 0;
    std::string token;
    
    while ((pos = ByteStr.find(delimiter)) != std::string::npos) {
    
        token = ByteStr.substr(0, pos); 
        uchar ucharToken = uchar(strtol(token.c_str(), NULL, 16));
        vct.push_back(ucharToken);
        ByteStr.erase(0, pos + delimiter.length());
    
    }          
    
    cv::Mat img = cv::imdecode(vct, cv::IMREAD_GRAYSCALE);
    cv::namedWindow("MyWindow");
    cv::imshow("MyWindow",img);
    

    【讨论】:

    • 感谢您的有用回答@Miki
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多