今天尝试用OpenCV遍历文件夹中所有图像,并改变其尺寸大小(resize)
搜到这种方法connect,还没有尝试。
先试了一下简单的方法,首先,因为不知道文件名,比较麻烦。
最开始得到的图像如下
我简单地以为只要改变尾数就行了,code的时候发现没那没简单。
比如说:
#include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; //define Width and Height const int width = 600; const int height = 800; int main() { Mat src; int i; string src_image_name = "D:\\Documents\\visual studio 2012\\Projects\\haaring_resize\\haaring_resize\\before\\"; string src_image_name_after = "D:\\Documents\\visual studio 2012\\Projects\\haaring_resize\\haaring_resize\\after\\"; string src_image_name1 = src_image_name; char num[12],num1[8] = "2008010",num2[5] = ".jpg"; for ( i = 1; i <= 12; i++) { itoa(i,num,10); src_image_name += num1; src_image_name += num; src_image_name += num2; cout<<src_image_name<<endl; src = imread(src_image_name,CV_LOAD_IMAGE_COLOR); imshow(src_image_name,src); Mat dst(width,height,src.type()); //resize(src,dst,dst.size(),0,0,INTER_LINEAR); //imshow(src_image_name,dst); imwrite(src_image_name_after+src_image_name,dst); src_image_name = src_image_name1; } system("pause"); return 0; }很明显,2008010后面只有尾数从1到9,超过九就是10了,运行时就会报错。
于是我想了一个办法,首先全选所有源图片,然后重命名。在第一张上输入1,其他的图像就变成了这样
这样,后面只需要改变括号中的数字,for循环就搞定了。
尝试如下:
#include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; //define Width and Height const int width = 60; const int height = 80; int main() { Mat src; int i; string src_image_name = "D:\\Documents\\visual studio 2012\\Projects\\haaring_resize\\haaring_resize\\before\\"; string src_image_name_after = "D:\\Documents\\visual studio 2012\\Projects\\haaring_resize\\haaring_resize\\after\\"; string src_image_name1 = src_image_name; char num[12],num1[4] = "1 (",num2[6] = ").jpg"; string num3 = ".jpg"; for ( i = 1; i <= 12; i++) { itoa(i,num,10); src_image_name += num1; src_image_name += num; src_image_name += num2; cout<<src_image_name<<endl; src = imread(src_image_name,CV_LOAD_IMAGE_COLOR); imshow(src_image_name,src); Mat dst(width,height,src.type()); resize(src,dst,dst.size(),0,0,INTER_LINEAR); imshow(src_image_name,dst); imwrite(src_image_name_after+num+num3,dst); src_image_name = src_image_name1; } waitKey(0); system("pause"); return 0; }
这样就可以了,但是一定要在工程中建立before和after文件夹。
before文件夹:
after文件夹: