由于项目需要,需要保存图片保存到文件夹。
演示步骤:
1.加载图片
Mat img = cv::imread("apple.jpg");//加载并显示图片
imshow("Image", img);
2.准备文件夹名和图片名
文件夹名=当前时间 年月日
图片名=当前时间 时分秒
QDateTime time = QDateTime::currentDateTime();
QString fullPath = time.toString("yyyyMMdd");
QString filePath = time.toString("MMddHHmmss");
3.判断文件夹存不存在,不存在则创建文件夹
参考:https://blog.csdn.net/lusirking/article/details/51644782
// 判断文件夹是否存在,不存在则创建
QDir dir(fullPath);
if(!dir.exists()){
bool ismkdir = dir.mkdir(fullPath);
if(!ismkdir)
qDebug() << "Create path fail" << endl;
else
qDebug() << "Create fullpath success" << endl;
}
else{
qDebug() << "fullpath exist" << endl;
}
滴滴滴:Create path fail
将:bool ismkdir = dir.mkdir(fullPath);
改成:bool ismkdir = dir.mkpath(fullPath);
会发现在当前目录里生成了20190801/20190801(在当前目录下生成了20190801文件夹,但是20190801文件夹里面又包含了一个20190801文件夹)。
参考:https://www.jianshu.com/p/cf39710e2e4b
因为我这里用的是dir.mkpath,所以实际上创建的目录为dir的路径 + fullpath的路径。难怪mkdir创建失败
将:bool ismkdir = dir.mkdir(fullPath);
换成:bool ismkdir = Qdir().mkdir(fullPath);
搞定,在执行目录下生成了一个空文件夹
4.保存图片
std::string str= QString("%1/%2.jpg").arg(fullPath).arg(filePath).toStdString();
imwrite(str, img);
完整main函数代码如下:
#include "opencvmat.h"
#include <QApplication>
#include <QDateTime>
#include <QDir>
#include <QString>
#include <QDebug>
#include <iostream>
#include <string.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Mat img = cv::imread("apple.jpg");//加载图片,延时2后自动关闭窗口
imshow("Image", img);
QDateTime time = QDateTime::currentDateTime();
QString fullPath = time.toString("yyyyMMdd");
QString filePath = time.toString("MMddHHmmss");
// 判断文件夹是否存在,不存在则创建
QDir dir(fullPath);
if(!dir.exists()){
bool ismkdir = QDir().mkdir(fullPath);
if(!ismkdir)
qDebug() << "Create path fail" << endl;
else
qDebug() << "Create fullpath success" << endl;
}
else{
qDebug() << "fullpath exist" << endl;
}
std::string str= QString("%1/%2.jpg").arg(fullPath).arg(filePath).toStdString();
imwrite(str, img);
waitKey(2000);
destroyAllWindows();
//opencvMat w;
//w.show();
return a.exec();
}