1.在CRMBCheckDoc.h中添加变量
public:
IplImage *TheImage; //定义图像指针,类型IplImage
IplImage *GrayImage;
2.CRMBCheckDoc类初始化和析构函数
CRMBCheckDoc::CRMBCheckDoc()
{
// TODO: add one-time construction code here
TheImage = NULL; //把图像指针赋值为NULL
GrayImage = NULL;//把灰度图像指针赋值为NULL
}
CRMBCheckDoc::~CRMBCheckDoc()
{
if (TheImage != NULL)
{
cvReleaseImage(&TheImage);
}
if (GrayImage != NULL)
{
cvReleaseImage(&GrayImage);
}
}
3.重载函数OnOpenDocument,并添加代码
BOOL CRMBCheckDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
if (!CDocument::OnOpenDocument(lpszPathName))
return FALSE;
//重新打开文件时,把已有的数据清空
if (TheImage != NULL)
{
cvReleaseImage(&TheImage);
}
if (GrayImage != NULL)
{
cvReleaseImage(&GrayImage);
}
//打开图像文件把图像相关的数付给TheImage指针
TheImage = cvLoadImage(lpszPathName,1);
//判断图像文件打开是否成功,如果没有成功提示开打失败
if (TheImage == NULL)
{
MessageBox(NULL,"打开文件失败!","操作失败",MB_OK);
}
return TRUE;
}
4在菜单中添加彩色图像转换为灰度图像菜单,并生成触发事件。代码如下:
void CRMBCheckDoc::OnSdGrbtogray()
{
//判断图像文件是否已经打开
if(TheImage == NULL)
{
MessageBox(NULL,"请先打开文件!","操作失败",MB_OK);
return ;
}
//创建保存灰度图像的图像指针
GrayImage = cvCreateImage(cvSize(TheImage->width,TheImage->height),IPL_DEPTH_8U,1);
//把彩色图像转换为灰度图像
cvCvtColor(TheImage,GrayImage,CV_RGB2GRAY);
//更新视图
UpdateAllViews(NULL);
}
5为保存添加触发事件,并添加代码:
void CRMBCheckDoc::OnFileSave()
{
if (GrayImage != NULL)
{
cvSaveImage("reason.bmp",GrayImage);
}
else
{
MessageBox(NULL,"还没有对图像进行处理无法保持","提示",MB_OK);
}
}
6在类CRMBCheckView中添加OnDraw函数代码:
CRMBCheckDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
HDC hDC = pDC->GetSafeHdc();
// TODO: add draw code for native data here
//显示打开的图像文件
if (pDoc->TheImage != NULL)
{
//创建显示图像文件的区域
CRect rect(0,0,pDoc->TheImage->width,pDoc->TheImage->height);
CImage img; //
img.CopyOf(pDoc->TheImage);//把Doc文件中的IplImage数据拷贝到CImage
img.DrawToHDC(hDC,&rect);//进行图像显示
}
//显示转化后的灰度图像
if (pDoc->GrayImage != NULL)
{
COLORREF *data;
CBitmap bm;
CDC *MemDC = new CDC;
int width = pDoc->GrayImage->width, height = pDoc->GrayImage->height;
pDC->SetBkMode(TRANSPARENT); //设置背景颜色为透明
int step = pDoc->GrayImage->widthStep / sizeof(uchar); //计算Doc中IplIamge存取的图像数据的步长
data = new COLORREF[width * height];//为data数据分配空间,大小为灰度图像的大小
//为data赋值
for (int i = 0;i != height;i++)
{
for (int j = 0;j != width;j++)
{
data[i * width + j] = RGB((pDoc->GrayImage->imageData[i * step + j]),(pDoc->GrayImage->imageData[i * step + j]),(pDoc->GrayImage->imageData[i * step + j]));
}
}
//create bitmap
bm.CreateBitmap(width,height,1,32,data);
//实现双缓冲,避免闪烁
MemDC->CreateCompatibleDC(pDC);
MemDC->SelectObject(&bm);
pDC->SetStretchBltMode(COLORONCOLOR);
pDC->StretchBlt(pDoc->TheImage->width + 10,0,width,height,MemDC,0,0,width,height,SRCCOPY);
//删除已经分配的内存空间
ReleaseDC(MemDC);
delete MemDC;
bm.DeleteObject();
delete[] data;
}
ReleaseDC(pDC);
7.编译程序并运行,运行结果如下: