2017-03-06 86 views
0

当我试图将二维数组转换为图像时,行和列变形。同样的图像不能被制作。OpenCV二维数组到图像转换

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; 
} 

我们是得了输出,

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] 

我们可以看到,输出和输入是不一样的。因此需要帮助重建相同的数据。

谢谢。

回答

0

失真输出的原因是你试图把2d int(32bit)数组放入unsigned char(8位)mat。为了解决这个问题,必须要么改变垫类型(CV_8U)到CV_32S或更改二维数组为unsigned char

+0

谢谢。它的工作。 – Baskar

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

这将给你相同的图像作为UCHAR。不需要使用double for循环。