OpenInventor到PCD:无法将RGB转换为十进制

时间:2012-07-22 18:53:57

标签: c++ opencv rgb point-cloud-library openinventor

我正在编写一个小程序来将OpenInventor文件转换为PCD文件。为此,我输入了两个文件,即OpenInventor文件和JPEG图像。纹理坐标是介于0.0和1.0之间的浮点值。

我使用OpenCV提取RGB值并以十进制格式返回,但以下功能似乎无法正常工作......

float get_color(cv::Mat img, float x, float y) {

    int i = x*img.cols;
    int j = y*img.rows;

    unsigned char R = img.ptr<unsigned char>(j)[3*i];
    unsigned char G = img.ptr<unsigned char>(j)[3*i+1];
    unsigned char B = img.ptr<unsigned char>(j)[3*i+2];

    return  R*pow(16,4) +
            G*pow(16,2) +
            B;
}

我用

加载图片
 cv::imread("filename.jpg", CV_LOAD_IMAGE_COLOR).

2 个答案:

答案 0 :(得分:1)

您的意思是将其作为32位整数返回吗?

unsigned int get_color(cv::Mat img, float x, float y) 
{

    int i = x*img.cols;
    int j = y*img.rows;

    unsigned char R = img.ptr<unsigned char>(j)[3*i];
    unsigned char G = img.ptr<unsigned char>(j)[3*i+1];
    unsigned char B = img.ptr<unsigned char>(j)[3*i+2];

    return  (R << 16) |
            (G << 8) |
            B;
}

或者您可能希望将其作为浮点数返回,在这种情况下,您需要执行以下操作

struct FloatColour
{
    float r;
    float g;
    float b;
};

float get_color(cv::Mat img, float x, float y) 
{

    int i = x*img.cols;
    int j = y*img.rows;

    unsigned char R = img.ptr<unsigned char>(j)[3*i];
    unsigned char G = img.ptr<unsigned char>(j)[3*i+1];
    unsigned char B = img.ptr<unsigned char>(j)[3*i+2];

    FloatColour retCol;
    retCol.r = R / 255.0f;
    retCol.g = G / 255.0f;
    retCol.b = B / 255.0f;
    return retCol;
}

答案 1 :(得分:1)

我在PCL的标题“point_types.hpp”(PCL版本:1.5.1)中的评论中找到了我自己问题的答案:

  

由于历史原因(PCL最初是作为ROS包开发的),   RGB信息被打包成一个整数并转换为浮点数。   这是我们希望在不久的将来删除,但在   同时,以下代码段应该可以帮助您打包和解压缩   PointXYZRGB结构中的RGB颜色:

uint8_t r = 255, g = 0, b = 0;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);

在重构和其他一些错误修复之后,该函数变为:

float get_color(cv::Mat img, float s, float t){

        int j = (1.0 - s)*(float)img.cols;
        int i = (1.0 - t)*(float)img.rows;

        uint8_t R = img.at<cv::Vec3b>(i,j)[2];
        uint8_t G = img.at<cv::Vec3b>(i,j)[1];
        uint8_t B = img.at<cv::Vec3b>(i,j)[0];

        uint32_t rgb_32 = ((uint32_t)R << 16 | (uint32_t)G << 8 | (uint32_t)B);

        return *reinterpret_cast<float*>(&rgb_32);
}