您的位置:首页 > 运维架构

MFC和OpenCV 对话框依次显示文件夹内的图片

2016-10-09 19:54 435 查看
MFC和OpenCV 对话框依次显示文件夹内的图片

1.新建基于对话框的MFC的项目。

2.插入Picture Control 控件,设ID为 IDC_showwindow

三个按钮 “打开图片”,“首幅图片”,“下一幅图片”

3.分别添加响应函数

这里主要使用文件搜索函数_findfirst , _findnext 和结构体
struct _finddata_t


头文件是
<io.h>


long _findfirst( char *filespec, struct _finddata_t *fileinfo );


返回值:如果查找成功的话,将返回一个long型的唯一的查找用的句柄(就是一个唯一编号)。这个句柄将在_findnext函数中被使用。若失败,则返回-1。

参数:

filespec:标明文件的字符串,可支持通配符。比如:*.c,则表示当前文件夹下的所有后缀为C的文件。

fileinfo :这里就是用来存放文件信息的结构体的指针。这个结构体必须在调用此函数前声明,不过不用初始化,只要分配了内存空间就可以了。函数成功后,函数会把找到的文件的信息放入这个结构体中。

int _findnext( long handle, struct _finddata_t *fileinfo );


返回值:若成功返回0,否则返回-1。

参数:

handle:即由_findfirst函数返回回来的句柄。

fileinfo:文件信息结构体的指针。找到文件后,函数将该文件信息放入此结构体中。


int _findclose( long handle );


返回值:成功返回0,失败返回-1。

参数:

handle :_findfirst函数返回回来的句柄。

打开图片响应函数具体实现

struct _finddata_t fileinfo;
string tstring;
CString tFileName;
CFileDialog tDlg(TRUE);
if(tDlg.DoModal() == IDOK) {
tFileName = tDlg.GetPathName();
tstring = tFileName.GetBuffer(0);//文件完整路径
}

int pos = tstring.find_last_of('\\', tstring.length());
subpath = tstring.substr(0, pos);  // Return the directory without the file name

curr = subpath+"\\*.bmp";

if((handle=_findfirst(curr.c_str(),&fileinfo))==-1L)
{
MessageBox("error", "no image loaded!", MB_OK);
return ;
}

else
{
in_name = subpath + "\\" + fileinfo.name ;
renderScene(in_name);//显示第一张图片在对话框
}


下一幅图像命令的实现代码 :

if(!(_findnext(handle,&fileinfo)))
{

in_name = subpath + "\\" +fileinfo.name;
renderScene(in_name);
}
else
{
_findclose(handle);

}


图片显示在MFC对话框中 ,使用了CvvImage类,OpenCV2.0以后没有了此类,不过网上有单独的CvvImage文件。

void CtestopencvDlg::renderScene(string tstring)

{

Mat mat = cv::imread(tstring, 1);

CRect rect;
GetDlgItem(IDC_showwindow)->GetClientRect(&rect);

float widRat = (float)rect.Width() / mat.cols;
float heiRat = (float)rect.Height() / mat.rows;
float resRat = widRat < heiRat ? widRat : heiRat;
int resWid = mat.cols * resRat;
int resHei = mat.rows * resRat;
cv::resize(mat, mat2, cv::Size(resWid, resHei)); // 调整
CDC* pDC = GetDlgItem(IDC_showwindow)->GetDC();
HDC hDC = pDC->GetSafeHdc();
IplImage img = mat2;
CvvImage cimg;
cimg.CopyOf( &img );

GetDlgItem(IDC_showwindow)->GetClientRect(&rect);
int tlx = rect.TopLeft().x;
int tly = rect.TopLeft().y;
int brx = tlx + mat2.cols - 1;
int bry = tly + mat2.rows - 1;
CRect drawRect;
drawRect.SetRect(tlx, tly, brx, bry);
cimg.DrawToHDC(hDC, &drawRect);//MFC空间绘图

ReleaseDC( pDC );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MFC显示图片