简体   繁体   English

OpenCV 2D阵列到图像的转换

[英]OpenCV 2D-Array to Image Conversion

When I tried to convert a 2D array to image, the rows and columns are getting distorted. 当我尝试将2D数组转换为图像时,行和列变得失真。 Same Image cant be made. 无法制作相同图像。

using namespace cv;
using namespace std;


int main()
{
     float val;
     int val1[3][3];

     Mat imm = (Mat_<float>(3,3) << 12, 13, 45, 11, 191, 255, 62, 27, 0);
     if (imm.empty()) //check whether the image is loaded or not
     {
         cout << "Error : Image cannot be loaded..!!" << endl;
         //system("pause"); //wait for a key press
         return -1;
     }

     for (int y = 0; y < imm.rows; ++y)
     {
         float* row_ptr = imm.ptr<float>(y);
         for (int x = 0; x < imm.cols; ++x)
         {
              val = row_ptr[x];
              val1[y][x]=val;
              if(x%3==0)
              cout<<"\n";
              cout<<val<<"\t";

         }
     }


     Mat out_img(3,3,CV_8U ,val1);
     cout<<"\n\n\n output= "<<out_img;
     cout<<"\n\n\n\n"<<"Input= "<<imm;
 }

The output we got is, 我们得到的输出是

12  13  45  
11  191 255 
62  27  0   


 output= [ 12,   0,   0;
   0,  13,   0;
   0,   0,  45]



Input= [12, 13, 45;
 11, 191, 255;
 62, 27, 0]

We can see that output and input were not the same. 我们可以看到输出和输入不一样。 So need help in reconstruction of the same data. 因此在重建相同数据时需要帮助。

Thanks. 谢谢。

The reason for distorted output is you are trying to put 2d int (32bit) array into unsigned char(8 bit) mat. 输出失真的原因是您试图将2d int(32bit)数组放入unsigned char(8 bit)mat中。 To correct this, you must either change mat type(CV_8U) to CV_32S or change 2d array to unsigned char 若要更正此问题,您必须将垫类型(CV_8U)更改为CV_32S或将2d数组更改为unsigned char

Mat im2;
imm.convertTo(CV_8U, im2);

This will give you the same image as uchar. 这将为您提供与uchar相同的图像。 No need to use the double for loop. 无需使用double for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM