用opencv读取图像,并且显示

//打开一幅图像
void Cload_image_v1View::OnFileOpen()
{
 CString fileName;//存储从打开对话框获得的路径名称,以Cstring类型
 string imageName;//存储从打开对话框获得的路径名称,以string类型

 CFileDialog dlg(true);
 if (dlg.DoModal()!=IDOK)
 {
  return;
 }
 fileName=dlg.GetFileName();//将字符集改为多字节字符集后Cstring到string类型的转换,unicode的转换方法见博客
 imageName=fileName.GetBuffer();
 m_imgData= imread(imageName);//opencv中函数读入图像

 if(m_imgData.empty())//如果读入图像失败
 {
  MessageBox("could not find the image");
  return ;
 }

 namedWindow("image",1);  //创建窗口
 imshow("image", m_imgData); //显示图像
 waitKey();     //等待按键,按键盘任意键返回
 
 // TODO: 在此添加命令处理程序代码
}

 

void Cload_image_v1View::OnShowBmp()
{
 int nWidth;  //图像的宽度
 int nHeight; //图像的高度
 int nChannel; //颜色通道的数目,为1时表示有颜色表;为3时没有颜色表
 int nDepth; 
 int nBits;  //每个像素所需要的位数 1,4,8,24
 int nColors; //颜色表的项数2.16.256
 int i;

 nWidth=m_imgData.cols;
 nHeight=m_imgData.rows;
 nDepth=m_imgData.depth();
 nChannel=m_imgData.channels();

 nBits=(8<<(nDepth/2))*nChannel;
 if (nBits>8)
  nColors=0;
 else
  nColors=1<  if (nBits==24)
 {
  nBits=32;
 }
 
 


 

 //位图信息头
 BITMAPINFOHEADER bmiInfoHeader={40,0,0,1,8,BI_RGB,0,0,0,0,0};
 bmiInfoHeader.biWidth=nWidth;
 bmiInfoHeader.biHeight=nHeight;
 bmiInfoHeader.biBitCount=nBits;

 
 
 //位图颜色表
 RGBQUAD*colorTab;
 int MaxColors=256;
 colorTab=new RGBQUAD[MaxColors];
 for (i=0;i<256;i++)
 {
  colorTab[i].rgbBlue=colorTab[i].rgbGreen=colorTab[i].rgbRed=(BYTE)i;
 }

 //位图信息头
 LPBITMAPINFO lpBmi;
 lpBmi=(LPBITMAPINFO)malloc(40+4*nColors);
 memcpy(lpBmi,&bmiInfoHeader,40);
 


 //位图数据
 unsigned char*pDibBits=0; //存储图像中的数据,由下向上,由左向右
 unsigned char*pBmpData=0; //指向bmp图像的指针
 unsigned char*pImgData=0; //指向Mat数据区的指针
 pImgData=m_imgData.data;
 int x,y;

 //表示灰度图像
 if (nChannel==1)
 {
  memcpy(lpBmi->bmiColors,colorTab,1024);
  pDibBits=new unsigned char[nWidth*nHeight];
  for (x=0;x   {
   pBmpData=pDibBits+(nHeight-1-x)*nWidth;
   memcpy(pBmpData,pImgData,nWidth);
   pImgData=pImgData+nWidth;
  }
 }
 //表示真彩色图像
 else if (nChannel==3)
 {
  pDibBits=new unsigned char[nWidth*nHeight*4];
  for (x=0;x   {
   pBmpData=pDibBits+(nHeight-1-x)*nWidth*4;
   for (y=0;y    {
    memcpy(pBmpData,pImgData,3);
    pBmpData[3]=255;
    pBmpData=pBmpData+4;
    pImgData=pImgData+3;
   }
  }
 }
 

//显示图像

 CDC*pdc=GetDC();
 SetStretchBltMode(pdc->m_hDC,HALFTONE);
 StretchDIBits(pdc->m_hDC,0,0,nWidth,nHeight,0,0,nWidth,nHeight,pDibBits,lpBmi,BI_RGB,SRCCOPY);
 delete [] pDibBits;
 free(lpBmi);
 ReleaseDC(pdc);
 

 // TODO: 在此添加命令处理程序代码
}

 

你可能感兴趣的:(opencv,MFC)