用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<<nBits;
 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<nHeight;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<nHeight;x++)
  {
   pBmpData=pDibBits+(nHeight-1-x)*nWidth*4;
   for (y=0;y<nWidth;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: 在此添加命令处理程序代码
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值