簡體   English   中英

將圖像輸出回Matlab Mex

[英]outputting image back to matlab Mex

我正在嘗試將圖像從我的mex文件輸出回我的matlab文件,但是當我在matlab中打開它時,它是不正確的。

帶有mex文件的輸出圖像是正確的

我試圖切換mwSize的方向以及在new_img.at<int>(j, i)交換ij ;

Mat image = imread(mxArrayToString(prhs[0]));
Mat new_img(H,W, image.type(), Scalar(0));
// some operations on new_img
imshow( "gmm image", image ); //shows the original image
imshow( "gmm1 image", new_img ); //shows the output image
waitKey( 200 );  //both images are the same size as desired

mwSize nd = 2;
mwSize dims[] = {W, H};

plhs[0] = mxCreateNumericArray(nd, dims, mxUINT8_CLASS, mxREAL);
if(plhs == NULL) {
  mexErrMsgTxt("Could not create mxArray.\n");     
}     
char* outMat = (char*) mxGetData( plhs[0]);

for (int i= 0; i < H; i++)
{
  for (int j = 0; j < W; j++)
  {       
    outMat[i +j*image.rows] = new_img.at<int>(j, i);       
  }
}

這在墊子文件中

gmmMask = GmmMex2(imgName,rect);
imshow(gmmMask); % not the same as the output image. somewhat resembles it, but not correct.

因為您已經暗示這是彩色圖像 ,所以這意味着您要考慮矩陣的三個部分。 您的代碼僅考慮一片。 首先,您需要確保聲明正確的圖像尺寸。 在MATLAB中,第一維始終是行數,而第二維是列數。 現在,您還必須在此之上添加通道數。 我假設這是RGB圖像,所以有三個通道。

因此,將您的dims更改為:

mwSize nd = 3;
mwSize dims[] = {H, W, nd};

nd更改為3很重要,因為這將允許您創建3D矩陣。 您只有2D矩陣。 接下來,確保要訪問cv::Mat對象中正確位置的圖像像素。 在嵌套的for循環對中訪問圖像像素的方式采用行為主的方式(先在列上迭代,然后在行上迭代)。 這樣,您需要在i訪問行和j訪問列時交換ij 需要訪問彩色圖像的通道,因此需要另一個for循環來進行補償。 對於灰度情況,盡管如此,您已經適當地補償了MATLAB MEX矩陣的列主內存配置。 這已得到驗證,因為j訪問列,並且您需要按行數跳過才能訪問下一列。 但是,要適應彩色圖像,還必須按image.rows*image.cols跳過以轉到下一層像素。

因此,您的for循環現在應為:

for (int k = 0; k < nd; k++) {
    for (int i = 0; i < H; i++) { 
        for (int j = 0; j < W; j++) {
            outMat[k*image.rows*image.cols + i + j*image.rows] = new_img.at<uchar>(i, j, k);
        }
    }
}

請注意,像素容器很可能是8位無符號字符,因此必須將模板更改為uchar not int 這也可以解釋您的程序為什么崩潰的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM