Check image type using a C++ 11 compatible method

This commit is contained in:
Matt McWilliams 2023-02-03 23:10:50 -05:00
parent 5d5275bf25
commit 5c06eff4b5
1 changed files with 30 additions and 14 deletions

View File

@ -1,29 +1,38 @@
#include <iostream> #include <iostream>
#include <opencv2/core.hpp> #include <opencv2/core.hpp>
#include <sys/stat.h> #include <sys/stat.h>
#include <filesystem> // C++17 #include <string>
#include <vector>
#include <algorithm>
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace std; using namespace std;
using namespace cv; using namespace cv;
string supportedExt[10] = { std::vector<std::string> supportedExt = {
".jpg", ".JPG", "jpg", "JPG",
".jpeg", ".JPEG", "jpeg", "JPEG",
".png", ".PNG", "png", "PNG",
".tif", ".TIF", "tif", "TIF",
".tiff", ".tiff" "tiff", "tiff"
}; };
inline bool file_exists (const std::string& name) { inline bool in_array(const std::string &value, const std::vector<std::string> &array)
struct stat buffer; {
return (stat (name.c_str(), &buffer) == 0); return std::find(array.begin(), array.end(), value) != array.end();
} }
inline bool is_image (const std::string& name) { inline bool file_exists (const std::string& name)
fs::path filePath = name; {
if (filePath.extension() == ".jpg") struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
inline bool is_image (const std::string& name)
{
string ext = name.substr(name.find_last_of(".") + 1);
return in_array(ext, supportedExt);
} }
int main(int argc, char** argv) int main(int argc, char** argv)
@ -40,11 +49,18 @@ int main(int argc, char** argv)
return -2; return -2;
} }
if (!file_exists(input)) { if (!file_exists(input))
{
cerr << "File " << input << " does not exist." << endl; cerr << "File " << input << " does not exist." << endl;
return -3; return -3;
} }
if (!is_image(input))
{
cerr << "File " << input << " is not a valid image." << endl;
return -4;
}
cout << "Using image " << input << "." << endl; cout << "Using image " << input << "." << endl;
return 0; return 0;