【问题标题】:converting an RGB image to 1d Array using opencv使用opencv将RGB图像转换为一维数组
【发布时间】:2020-07-17 19:21:18
【问题描述】:

我正在尝试读取 RGB 图像并将其转换为一维数组。打印值时,我知道我为转换编写的逻辑不正确。有人可以帮我吗?此外,当我尝试定义 image_array 时,它给了我一个错误。

表达式必须有常数值。

我已经发布了下面的代码。

//reading the images
Mat img_rev = imread("C:/Users/20181217/Desktop/images/imgs/output_rev.png");
cvtColor(img_rev, img_rev, COLOR_BGR2RGB);
//get the image height,width and number of channles to convert into an array
int const img_height = img_rev.rows;
int const img_width = img_rev.cols;
int const img_channels = img_rev.channels();
//printing out the dimenesions
cout << img_height << ", " << img_width << ", " << img_channels; //256,512,3
//starting the conversion to array
uchar image_array[256 * 512 * 3];
//uchar image_array[img_rev.rows * img_rev.cols * img_rev.channels()]; error:expression must have a constant value
//uchar image_array[img_height * img_width * img_channels]; error:expression must have a constant value

for (int i = 0; i < img_rev.rows; i++)
{
    for (int j = 0; j < img_rev.cols; j++)
    {
        if(i==200 && j==200)
            cout << endl << "value at (200,200) of green in MAT is :" << (int)img_rev.at<Vec3b>(i, j)[1] << endl; //printing the value at (200,200) of green channel
    }
}

//conversion from image to 1d array
for (int i = 0; i < img_rev.rows; i++)
{
    for (int j = 0; j < img_rev.cols; j++)
    {
        image_array[(i*img_rev.rows) + (j * 3)] = img_rev.at<Vec3b>(i, j)[0]; //R  
        image_array[(i*img_rev.rows) + (j * 3) + 1] = img_rev.at<Vec3b>(i, j)[1]; //G
        image_array[(i*img_rev.rows) + (j * 3) + 2] = img_rev.at<Vec3b>(i, j)[2]; //B
    }
}
cout << endl << "value at (200,200) of green in array is :" << (int)image_array[(200*img_rev.cols) + 200 +1];
cout << endl << "done";
waitKey(100000);

如果有人可以为此提供一些帮助,我将不胜感激。 提前致谢。

【问题讨论】:

    标签: c++ opencv image-processing


    【解决方案1】:

    如果数组没有固定大小,就像在你的例子中一样,你应该使用动态分配的数组。声明uchar* image_array = new uchar[img_rev.total() * img_rev.channels()] 可能是一个解决方案,但您需要手动delete 以在不再使用时释放内存。

    为了不处理跟踪删除,我建议使用std::vector

    std::vector<uchar> image_array(img_rev.total() * img_rev.channels());
    

    一旦数组被动态分配,您就可以使用您的方法。


    converting cv::Mat to std::vector 有一个更简单的方法。在您的情况下,由于img_rev 是由imread 创建的,因此我们确定数据是连续的,因此我们可以执行以下操作:

    std::vector<uchar> image_array = img_rev.data;
    

    【讨论】:

    • 感谢您的建议,对您有所帮助。您还可以就如何将 3d 数组作为 1d 数组访问的问题的第二部分提供一些建议
    • Mat 类有一个名为reshape 的成员函数。您可以使用它将 3D 图像转换为 1D。我敢打赌,这个问题已经被问到了。你可以在这个网站上找到它。
    • @AnoopKrishna 将 Mat 转换为矢量的链接还有另一个答案,即 it can be done in two lines。它使用reshape
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 2016-11-24
    • 2014-12-28
    • 2019-06-07
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多