从字符串到 unsigned char 的转换错误

Conversion error from string to unsigned char

我正在研究 opencv。我正在从文本文件中读取颜色值(格式为:123,32,123)。我需要将这些值插入到 vector(Vec3b)origColors 中。下面是我的代码。

ifstream myfile;
string line;
string delimiter = ",";
string temp;
vector<uchar> colors;
vector<Vec3b> origColors;
myfile.open("DedicatedColors.txt");
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        while(line.find(",",0) != string::npos)
        {
            size_t pos = line.find(",",0);
            temp = line.substr(0, pos);
            line.erase(0,pos+1);
            unsigned char* val=new unsigned char[temp.size() + 1]();
            copy(temp.begin(), temp.end(), val);
            colors.push_back(val); //Error Reference to type 'const value_type' (aka 'const unsigned char') could not bind to an lvalue of type 'unsigned char *'
        }
        dedColors.push_back(Vec3b(colors[0],colors[1],colors[2]));
        colors.clear();
    }
    myfile.close();
}

有人可以帮我修复这段代码吗?提前致谢。

"Error Reference to type 'const value_type' (aka 'const unsigned char') could not bind to an lvalue of type 'unsigned char *'"

你有一个无符号字符向量,其 push_back() 方法只接受无符号字符,而你正试图推回一个无符号字符 指针 。如果你真的需要使用 unsigned char * 而不能只使用 std::string,你的颜色向量必须是 std::vector<unsigned char*>.

假设 Vec3B 只接受 std::vector<unsigned char*>,我实际上倾向于使用 std::string 直到最后,此时你可以调用 std::string::c_str 来获得一个以空字符结尾的字符串.

像这样:

std::ifstream myfile("DedicatedColors.txt");

std::string line;

std::vector<Vec3b> origColors;

if (myfile.is_open())
{
    while (std::getline(myfile,line))
    {
        std::vector<std::string> colors;

        std::string::const_iterator last, itr;

        last = itr = line.begin();

        while (std::find(itr, line.end(), ',') != line.end())
        {
            colors.push_back(std::string(last, itr));

            last = itr++;
        }

        dedColors.push_back(Vec3b(colors[0].c_str(),colors[1].c_str(),colors[2].c_str()));
    }
}

编辑:我实际上只是注意到您可能正在尝试将 RGB 值转换为无符号字符,而不是像现在这样实际使用字符串。

然后,使用 std::vector<unsigned char> 而不是 std::vector<std::string> 并使用 std::stoi 将作为 std::string 获得的 RGB 值从 std::getline 转换为int,然后像这样传递它们:

colors.push_back(std::stoi(std::string(last, itr)));

正如已经指出的那样,您正在尝试 push_back 一个 unsigned char* 到一个只接受 unsigned char 的向量中:

colors.push_back(val);

如果你可以访问boost库,你可以试试下面的代码(未测试):

#include <boost/lexical_cast.hpp>
// ... <your code> ...
while (getline(myfile, line)) {
    vector<string> colors;
    boost::split(line, colors, boost::is_any_of(','));
    dedColors.push_back(Vec3b(boost::lexical_cast<uchar>(colors[0]),
                              boost::lexical_cast<uchar>(colors[1]),
                              boost::lexical_cast<uchar>(colors[2])));
}
// ... <continue with your code> ...