昨天已經寫過轉換影像類型這一篇網誌,然而那只能一個檔一個檔慢慢轉換,如今我有成千上萬張相片,想要一次搞定資料夾內所有的影像檔,該怎麼做呢?
若我有Ulead Photo Explorer、ACDSee等可以批次轉檔的軟體,或許就不用寫程式了?哈~這麼說也是,前提是我要有權限使用這類的軟體,因為上述兩者都非免費軟體,因此取得上就是一個問題要解決。
當然有些看圖軟體是免費的,但我不想花時間去找,於是乎剛好會寫OpenCV,倒不如自己動手寫個簡易版的影像轉檔程式,可以根據自己的需求做設定,相當有趣呢!
首先需要引用dirent.h函式庫,使用DIR和dirent這兩個結構,前者dir存放開啟資料夾opendir(“."),後者entry存放讀取資料夾readdir(dir)。
「“."」表示當前資料夾,可以用相對位置或絕對位置。來看一下程式碼:
/**
Theme: Transform Image Type (Batch)
compiler: Dev C++ 4.9.9.2
Date: 100/05/15
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
#include<iomanip>
#include <cv.h>
#include <highgui.h>
#include <string.h>
#include <dirent.h>
using namespace std;
int main(){
DIR *dir;
dirent *entry;
char *StrPointer;
char picFormat[5];
IplImage *image;
cout<<"請輸入要轉檔副檔名之名稱\n";
cout<<"(bmp,dib,jpg,jpeg,jpe,jp2,exr,png,tif,tiff,pbm,pgm,ppm,ras,sr)\n\n-> ";
cin>>picFormat;
LARGE_INTEGER startTime,endTime,fre;
double times;
QueryPerformanceFrequency(&fre); //取得CPU頻率
QueryPerformanceCounter(&startTime); //取得開機到現在經過幾個CPU Cycle
//doing something
dir=opendir(".");//開啟程式檔所在位置資料夾
while(entry=readdir(dir)){
if((StrPointer=strstr(entry->d_name,".bmp"))||
(StrPointer=strstr(entry->d_name,".dib"))||
(StrPointer=strstr(entry->d_name,".jpg"))||
(StrPointer=strstr(entry->d_name,".jpeg"))||
(StrPointer=strstr(entry->d_name,".jpe"))||
(StrPointer=strstr(entry->d_name,".jp2"))||
(StrPointer=strstr(entry->d_name,".exr"))||
(StrPointer=strstr(entry->d_name,".png"))||
(StrPointer=strstr(entry->d_name,".tif"))||
(StrPointer=strstr(entry->d_name,".tiff"))||
(StrPointer=strstr(entry->d_name,".pbm"))||
(StrPointer=strstr(entry->d_name,".pgm"))||
(StrPointer=strstr(entry->d_name,".ppm"))||
(StrPointer=strstr(entry->d_name,".ras"))||
(StrPointer=strstr(entry->d_name,".sr"))){
image=cvLoadImage(entry->d_name,0);//開啟影像
strncpy(StrPointer+1, picFormat, strlen(picFormat));//組合檔案名稱+副檔名
cvSaveImage(entry->d_name,image);//儲存影像
cvReleaseImage(&image);
cout<<entry->d_name<<endl;
}
}
//doing something
QueryPerformanceCounter(&endTime); //取得開機到程式執行完成經過幾個CPU Cycle
times=((double)endTime.QuadPart-(double)startTime.QuadPart)/fre.QuadPart;
cout << fixed << setprecision(20) << times << endl;
system("pause");
return EXIT_SUCCESS;
}
這裡需要注意的是,有時候副檔名會有大寫或小寫,如.jpg、.JPG,這時候就要大小寫都考慮進去轉換。而OpenCV支援的影像格式有bmp,dib,jpg,jpge,jpe,jp2,exr,png,tif,tiff,pbm,pgm,ppm,ras,sr。
這個程式碼還附上計算轉換時間,若需要大量轉檔的人,可以順便得知所花費的時間為何。
參考:GUI介面的製作-轉檔程式的實作。
隨意留個言吧:)~