如何使用OpenCV将数据保存到图像中?

时间:2017-01-11 03:11:52

标签: opencv

我使用cvLoadImage将图像(原始图像)读入CvMat,并通过中间数据块将其数据指针分配给另一个CvMat,然后使用cvShowImage显示此CvMat,但只有原始图像的一小部分区域是显示在与原始图像大小相同的窗口中。

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”时出现问题,但我不知道出了什么问题。

1 个答案:

答案 0 :(得分: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