2017-01-11 113 views
0

我使用cvLoadImage將圖像(原始圖像)讀入CvMat,並通過中間數據塊將其數據指針指定給另一個CvMat,然後使用cvShowImage顯示此CvMat,但只顯示原始圖像的一小部分區域在與原始圖像大小相同的窗口中。如何使用OpenCV將數據保存到圖像中?

char* filename = "image\\neuron.tif"; // an 8bits grayscale image 
IplImage* iplImage = cvLoadImage(filename); 
int width = iplImage->width; 
int height = iplImage->height; 
cvNamedWindow("Original", CV_WINDOW_AUTOSIZE); 
cvShowImage("Original", iplImage); // showed properly 
cvWaitKey(); 

CvMat* header = cvCreateMatHeader(height, width, CV_8UC1); 
CvMat* img_mat = cvGetMat(iplImage, header); 


unsigned char* img_host = (unsigned char*)malloc(height * width * sizeof(unsigned char));// the intermediate data block, on which I need to apply a cuda operation 
img_host = img_mat->data.ptr; 
CvMat* blur_mat = cvCreateMat(height, width, CV_8UC1); 
blur_mat->data.ptr = img_host; 
cvNamedWindow("Blurred", CV_WINDOW_AUTOSIZE); 
cvShowImage("Blurred", blur_mat); // the problem described 
cvWaitKey(); 

image output 其實,當我嘗試 「img_host = img_mat-> data.ptr」,但我不知道什麼是錯的問題發生。

+0

將cvLoadImage(文件名)更改爲cvLoadImage(文件名,CV_LOAD_IMAGE_GRAYSCALE); – eyllanesc

+1

您使用**陳舊** C api的任何特定原因? – Miki

+0

@Miki我想對圖像數據矩陣進行其他CUDA操作,所以我選擇C api ...真的很慚愧,我發佈了這個亂碼 – Zhang

回答

1

你的問題是,你的輸入圖像不是真正的單通道灰度8UC1圖像。你所看到的是圖像的前三分之一,其中每個BGR像素顯示爲3個灰度像素。

要解決此問題,您可以在灰度中讀取輸入內容,如@ eyllanesc在評論中建議的那樣:cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE);

或者,您需要聲明您的目標爲8UC3

在任何情況下,你的代碼是非常亂,有至少兩個內存泄漏的位置:

unsigned char* img_host = (unsigned char*)malloc(height * width * sizeof(unsigned char));// the intermediate data block, on which I need to apply a cuda operation 
img_host = img_mat->data.ptr; // LEAKS malloced buffer data 

CvMat* blur_mat = cvCreateMat(height, width, CV_8UC1); 
blur_mat->data.ptr = img_host; // LEAKS cvCreateMat() buffer data 

我真的建議你使用更高級別的C++ API與cv::Mat代替。

相關問題