I'm using opencv3.0.0 dev version with cmake.I installed opencv following this tutorial
http://docs.opencv.org/trunk/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation
After that I'm use the following cmake file to compile a simple face-detector:
cmake_minimum_required(VERSION 2.8)
project( face-detect )
find_package( OpenCV 3.0.0 EXACT REQUIRED )
add_executable( face-detect face-detect.cpp )
target_link_libraries( face-detect ${OpenCV_LIBS} )
Makefile is generated succefully, but when I compile the code there're missing classes under namespace cv:
face-detect.cpp:15: error: 'CommandLineParser' is not a member of 'cv'
cv::CommandLineParser parser(argc, argv, keys);
^
face-detect.cpp:23: error: invalid initialization of reference of type 'cv::InputArray {aka const cv::_InputArray&}' from expression of type 'const char*'
std::cout << cv::format("Error: cannot load cascade file!\n");
However it does find cv::CascadeClassifier. How to fix this problem?
This is the code for face-detect, I took it from internet:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
const char* keys =
{
"{i|input| |The source image}"
"{o|outdir| |The output directory}"
};
int main(int argc, const char** argv)
{
cv::CommandLineParser parser(argc, argv, keys);
std::string infile = parser.get<std::string>("input");
std::string outdir = parser.get<std::string>("outdir");
std::string cascade_file = "haarcascade_frontalface_alt.xml";
cv::CascadeClassifier cascade;
if (cascade_file.empty() || !cascade.load(cascade_file))
{
std::cout << cv::format("Error: cannot load cascade file!\n");
return -1;
}
cv::Mat src = cv::imread(infile);
if (src.empty())
{
std::cout << cv::format("Error: cannot load source image!\n");
return -1;
}
cv::Mat gray;
cv::cvtColor(src, gray, CV_BGR2GRAY);
cv::equalizeHist(gray, gray);
std::vector<cv::Rect> faces;
cascade.detectMultiScale(gray, faces, 1.2, 3);
std::cout << cv::format("0, %s (%dx%d)\n", infile.c_str(), src.cols, src.rows);
cv::Mat src_copy = src.clone();
for (int i = 0; i < faces.size(); i++)
{
std::string outfile(cv::format("%s/face-%d.jpg", outdir.c_str(), i+1));
cv::Rect r = faces[i];
cv::rectangle(src, r, CV_RGB(0,255,0), 2);
cv::imwrite(outfile, src_copy(r));
cv::imwrite(infile, src);
std::cout << cv::format("%d, %s (%dx%d)\n", i+1, outfile.c_str(), r.width, r.height);
}
return 0;
}
Related
I am new to SVM. I used to do object detection using HAAR Cascading. Now I am trying to implement SVM for object detection. I searched online and got to know about the basics.
I wanted to use libsvm while coding for c++. I am getting lots of problems.
Can anyone please explain step by step process of using it for object detection.
BTW I looked into opencv documentation of svm. But I am not able to do anything further.
Also I got this code for training my SVM and saving it into an xml file.
Now I want a code which can take this xml and detect objects in test cases.
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv.h>
#include <highgui.h>
#include <cvaux.h>
#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
using namespace cv;
int main ( int argc, char** argv )
{
cout << "OpenCV Training SVM Automatic Number Plate Recognition\n";
cout << "\n";
char* path_Plates;
char* path_NoPlates;
int numPlates;
int numNoPlates;
int imageWidth=150;
int imageHeight=150;
//Check if user specify image to process
if(1)
{
numPlates= 11;
numNoPlates= 90 ;
path_Plates= "/home/kaushik/opencv_work/Manas6/Pics/Positive_Images/";
path_NoPlates= "/home/kaushik/opencv_work/Manas6/Pics/Negative_Images/i";
}else{
cout << "Usage:\n" << argv[0] << " <num Plate Files> <num Non Plate Files> <path to plate folder files> <path to non plate files> \n";
return 0;
}
Mat classes;//(numPlates+numNoPlates, 1, CV_32FC1);
Mat trainingData;//(numPlates+numNoPlates, imageWidth*imageHeight, CV_32FC1 );
Mat trainingImages;
vector<int> trainingLabels;
for(int i=1; i<= numPlates; i++)
{
stringstream ss(stringstream::in | stringstream::out);
ss<<path_Plates<<i<<".jpg";
try{
const char* a = ss.str().c_str();
printf("\n%s\n",a);
Mat img = imread(ss.str(), CV_LOAD_IMAGE_UNCHANGED);
img= img.clone().reshape(1, 1);
//imshow("Window",img);
//cout<<ss.str();
trainingImages.push_back(img);
trainingLabels.push_back(1);
}
catch(Exception e){;}
}
for(int i=0; i< numNoPlates; i++)
{
stringstream ss(stringstream::in | stringstream::out);
ss << path_NoPlates<<i << ".jpg";
try
{
const char* a = ss.str().c_str();
printf("\n%s\n",a);
Mat img=imread(ss.str(), 0);
//imshow("Win",img);
img= img.clone().reshape(1, 1);
trainingImages.push_back(img);
trainingLabels.push_back(0);
//cout<<ss.str();
}
catch(Exception e){;}
}
Mat(trainingImages).copyTo(trainingData);
//trainingData = trainingData.reshape(1,trainingData.rows);
trainingData.convertTo(trainingData, CV_32FC1);
Mat(trainingLabels).copyTo(classes);
FileStorage fs("SVM.xml", FileStorage::WRITE);
fs << "TrainingData" << trainingData;
fs << "classes" << classes;
fs.release();
return 0;
}
Any help would be greatly appreciated.
Also I would love to have suggestions on how to implement libsvm for object detection.
This is a simple code which you could take a test with your xml file:
#include "highgui.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "cv.h"
#include <vector>
#include <string.h>
#include <ml.h>
#include <iostream>
#include <io.h>
using namespace cv;
using namespace std;
int main()
{
FileStorage fs;
fs.open("SVM.xml", FileStorage::READ);
Mat trainingData;
Mat classes;
fs["TrainingData"] >> trainingData;
fs["classes"] >> classes;
CvSVMParams SVM_params;
SVM_params.svm_type = CvSVM::C_SVC;
SVM_params.kernel_type = CvSVM::LINEAR; //CvSVM::LINEAR;
SVM_params.degree = 1;
SVM_params.gamma = 1;
SVM_params.coef0 = 0;
SVM_params.C = 1;
SVM_params.nu = 0;
SVM_params.p = 0;
SVM_params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 1000, 0.01);
CvSVM svm(trainingData, classes, Mat(), Mat(), SVM_params);
Mat src = imread("D:\\SVM\\samples\\\pos\\10.jpg");
Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
Mat p = gray.reshape(1, 1);
p.convertTo(p, CV_32FC1);
int response = (int)svm.predict( p );
if(response ==1 )
{
cout<<"this is a object!"<<endl;
cout<<endl;
}
else
{
cout<<"no object detected!"<<endl;
cout<<endl;
}
return 0;
}
by the way,it seems that there is little problem when runing your offered code,the result shows that:"opencv errror,Image step is wrongin cv::Mat::reshape".Had you met such situation before?Thank you.
i am trying to use the code given in the tutorial but it is not working. i am sure all the dependencies are there and the program is compiling but it giving me some errors related that some functions can not be found.
here is the code:
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/face.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace cv;
using namespace std;
static Mat norm_0_255(InputArray _src){
Mat src = _src.getMat();
Mat dst;
switch(src.channels()){
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';'){
std::ifstream file(filename.c_str(), ifstream::in);
if(!file){
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while(getline(file, line)){
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if(!path.empty() && !classlabel.empty()){
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
}
int main(int argc, const char *argv[]){
if(argc < 2){
cout << "usage: " << argv[0] << " <csv.ext> <output_folder> " << endl;
exit(0);
}
string output_folder = ".";
if(argc == 3){
output_folder = string(argv[2]);
}
string fn_csv = string(argv[1]);
vector<Mat> images;
vector<int> labels;
try{
read_csv(fn_csv, images, labels);
}catch(cv::Exception& e){
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
exit(1);
}
if(images.size() <= 1){
string error_message = "This demo needs at least 2 images to work. please add more images to your data set!";
CV_Error(CV_StsError, error_message);
}
int height = images[0].rows;
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
Ptr<cv::face::FaceRecognizer> model = cv::face::createEigenFaceRecognizer();
model->train(images, labels);
int predictedLabel = model->predict(testSample);
string result_message = format("Predicted class = %d / Actual class = %d ", predictedLabel, testLabel);
cout << result_message << endl;
Mat eigenvalues = model->getMat("eigenvalues");
Mat W = model->getMat("eigenvectors");
Mat mean = model->getMat("mean");
if(argc == 2){
imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
}else{
imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
}
// Display or save the Eigenfaces:
for (int i = 0; i < min(10, W.cols); i++) {
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
// get eigenvector #i
Mat ev = W.col(i).clone();
// Reshape to original size & normalize to [0...255] for imshow.
Mat grayscale = norm_0_255(ev.reshape(1, height));
// Show the image & apply a Jet colormap for better sensing.
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
// Display or save:
if(argc == 2) {
imshow(format("eigenface_%d", i), cgrayscale);
} else {
imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
}
}
// Display or save the image reconstruction at some predefined steps:
for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {
// slice the eigenvectors from the model
Mat evs = Mat(W, Range::all(), Range(0, num_components));
Mat projection = subspaceProject(evs, mean, images[0].reshape(1,1));
Mat reconstruction = subspaceReconstruct(evs, mean, projection);
// Normalize the result:
reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
// Display or save:
if(argc == 2) {
imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
} else {
imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
}
}
// Display if we are not writing to an output folder:
if(argc == 2) {
waitKey(0);
}
return 0;
}
CMakeLists.txt file:
cmake_minimum_required(VERSION 2.8)
project(faceReco)
find_package(OpenCV REQUIRED)
add_executable(faceReco faceReco.cpp)
target_link_libraries(faceReco ${OpenCV_LIBS})
Errors:
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp: In function ‘int main(int, const char**)’:
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:110:27: error: ‘class cv::face::FaceRecognizer’ has no member named ‘getMat’
Mat eigenvalues = model->getMat("eigenvalues");
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:111:17: error: ‘class cv::face::FaceRecognizer’ has no member named ‘getMat’
Mat W = model->getMat("eigenvectors");
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:112:20: error: ‘class cv::face::FaceRecognizer’ has no member named ‘getMat’
Mat mean = model->getMat("mean");
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:130:46: error: ‘COLORMAP_JET’ was not declared in this scope
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:130:58: error: ‘applyColorMap’ was not declared in this scope
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:143:75: error: ‘subspaceProject’ was not declared in this scope
Mat projection = subspaceProject(evs, mean, images[0].reshape(1,1));
^
/home/abdulaziz/workspace/OpenCV_Projects/FaceReco/faceReco.cpp:144:71: error: ‘subspaceReconstruct’ was not declared in this scope
Mat reconstruction = subspaceReconstruct(evs, mean, projection);
^
I am trying to implement face recognition using LDA with SIFT. I have an existing code of PCA with SIFT that uses SIFT to determine the keypoints and extract the descriptors and PCA to project those descriptors in the PCA sub-space. I am trying to achieve a similar functionality using LDA with SIFT.
I am trying to create an LDA object that will in turn call its member function 'project' but I get the following error:
OpenCV Error: Bad argument (The number of samples must equal the number of labels. Given 0 labels, 45 samples. ) in lda, file /home/shaurya/opencv-2.4.9/modules/contrib/src/lda.cpp, line 1015
terminate called after throwing an instance of 'cv::Exception'
what(): /home/mypath/opencv-2.4.9/modules/contrib/src/lda.cpp:1015: error: (-5) The number of samples must equal the number of labels. Given 0 labels, 45 samples. in function lda Aborted (core dumped)
The following is the PCA with SIFT code that I have executed:
#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/features2d/features2d.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
if(argc != 3)
{
cout << "Usage: ./output <training database path> <test image>" << endl;
return -1;
}
// Reading training images paths
vector<string> namesTrainingImages;
vector<string>::iterator stringIt;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (argv[1])) != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
if((strcmp(ent -> d_name, ".") == 0) || (strcmp(ent -> d_name, "..") == 0))
{
continue;
}
string tempName(string(argv[1]) + string(ent -> d_name));
namesTrainingImages.push_back(tempName);
}
}
closedir(dir);
vector<Mat> trainingImages;
vector<Mat>::iterator imageIt;
// Reading training images
for(stringIt = namesTrainingImages.begin(); stringIt != namesTrainingImages.end(); ++stringIt)
{
Mat tempImage;
tempImage = imread(*stringIt, CV_LOAD_IMAGE_GRAYSCALE);
waitKey(5000);
if(!tempImage.data )
{
cout << "Could not open or find the image" << std::endl ;
continue;
}
else
{
trainingImages.push_back(tempImage);
}
}
vector< vector<KeyPoint> > keypoints;
vector<Mat> descriptor;
vector<Mat>::iterator descriptorIt;
SIFT sift;
double percentage = 0.95;
for(imageIt = trainingImages.begin(); imageIt != trainingImages.end(); ++imageIt)
{
vector<KeyPoint> tempKeypoints;
Mat tempDescriptor1, tempDescriptor2, tempDescriptor3;
// Generating keypoints and descriptors from training images
sift.operator()(*imageIt, *imageIt, tempKeypoints, tempDescriptor1, false);
keypoints.push_back(tempKeypoints);
// Using PCA to project and then backProject the descriptors of training images
PCA pca(tempDescriptor1, Mat(), CV_PCA_DATA_AS_ROW, percentage);
pca.PCA::project(tempDescriptor1, tempDescriptor2);
tempDescriptor3 = pca.PCA::backProject(tempDescriptor2);
descriptor.push_back(tempDescriptor3);
}
// Reading the test image
Mat testImage;
testImage = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
waitKey(5000);
if(!testImage.data)
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
vector<KeyPoint> testKeypoints;
Mat testDescriptor, testDescriptor1, testDescriptor2;
// Generating teh keypoints and the descriptor of the test image
sift.operator()(testImage, testImage, testKeypoints, testDescriptor1, false);
// Using PCA to project and then backProject the descriptor of the test image
PCA pca(testDescriptor1, Mat(), CV_PCA_DATA_AS_ROW, percentage);
pca.PCA::project(testDescriptor1, testDescriptor2);
testDescriptor = pca.PCA::backProject(testDescriptor2);
// Flann based matching to determine the best matching training image
FlannBasedMatcher matcher;
vector<DMatch> matches;
vector<DMatch> good_matches;
int goodMatchesCtr = -1, tempCtr = -1, ctr = -1;
for(descriptorIt = descriptor.begin(); descriptorIt != descriptor.end(); ++descriptorIt)
{
++tempCtr;
vector<DMatch> tempMatches;
vector<DMatch> temp_good_matches;
int tempGoodMatchesCtr = 0;
double min_dist = 100;
matcher.match(testDescriptor, *descriptorIt, tempMatches);
for(int i = 0; i < testDescriptor.rows && i < (*descriptorIt).rows; ++i)
{
double dist = tempMatches[i].distance;
if(dist < min_dist)
{
min_dist = dist;
}
}
for(int i = 0; i < testDescriptor.rows && i < (*descriptorIt).rows; ++i)
{
if(tempMatches[i].distance <= max(2 * min_dist, 0.02))
{
temp_good_matches.push_back(tempMatches[i]);
++tempGoodMatchesCtr;
}
}
if(tempGoodMatchesCtr > goodMatchesCtr)
{
goodMatchesCtr = tempGoodMatchesCtr;
matches = tempMatches;
good_matches = temp_good_matches;
ctr = tempCtr;
}
}
// Displaying the test image alongside the best matching training image
Mat img_matches;
drawMatches(testImage, testKeypoints, trainingImages[ctr], keypoints[ctr], good_matches, img_matches, Scalar ::all(-1), Scalar ::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
for( int i = 0; i < (int)good_matches.size(); ++i )
{
printf( "-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx );
}
imshow("Good Matches", img_matches);
waitKey(0);
cout << "Executed!" << '\n';
return 0;
}
The following is the LDA with SIFT code that I am trying to execute:
#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/features2d/features2d.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
if(argc != 3)
{
cout << "Usage: ./output <training database path> <test image>" << endl;
return -1;
}
// Reading training images paths
vector<string> namesTrainingImages;
vector<string>::iterator stringIt;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (argv[1])) != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
if((strcmp(ent -> d_name, ".") == 0) || (strcmp(ent -> d_name, "..") == 0))
{
continue;
}
string tempName(string(argv[1]) + string(ent -> d_name));
namesTrainingImages.push_back(tempName);
}
}
closedir(dir);
vector<Mat> trainingImages;
vector<Mat>::iterator imageIt;
// Reading training images
for(stringIt = namesTrainingImages.begin(); stringIt != namesTrainingImages.end(); ++stringIt)
{
Mat tempImage;
tempImage = imread(*stringIt, CV_LOAD_IMAGE_GRAYSCALE);
waitKey(5000);
if(!tempImage.data )
{
cout << "Could not open or find a training image" << std::endl ;
continue;
}
else
{
trainingImages.push_back(tempImage);
}
}
vector< vector<KeyPoint> > keypoints;
vector<Mat> descriptor;
vector<Mat>::iterator descriptorIt;
SIFT sift;
for(imageIt = trainingImages.begin(); imageIt != trainingImages.end(); ++imageIt)
{
vector<KeyPoint> tempKeypoints;
Mat tempDescriptor;
// Generating keypoints and descriptors from training images
sift.operator()(*imageIt, *imageIt, tempKeypoints, tempDescriptor, false);
keypoints.push_back(tempKeypoints);
// Trying to use LDA to project the descriptors of training images
LDA lda(tempDescriptor, Mat());
lda.LDA::project(tempDescriptor);
descriptor.push_back(tempDescriptor);
}
// Reading the test image
Mat testImage;
testImage = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
waitKey(5000);
if(!testImage.data)
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
vector<KeyPoint> testKeypoints;
Mat testDescriptor;
// Generating the keypoints and the descriptor of the test image
sift.operator()(testImage, testImage, testKeypoints, testDescriptor, false);
// Trying to use LDA to project the descriptor of the test image
LDA lda(testDescriptor, Mat());
lda.LDA::project(testDescriptor);
// Flann based matching to determine the best matching training image
FlannBasedMatcher matcher;
vector<DMatch> matches;
vector<DMatch> good_matches;
int goodMatchesCtr = -1, tempCtr = -1, ctr = -1;
for(descriptorIt = descriptor.begin(); descriptorIt != descriptor.end(); ++descriptorIt)
{
++tempCtr;
vector<DMatch> tempMatches;
vector<DMatch> temp_good_matches;
int tempGoodMatchesCtr = 0;
double min_dist = 100;
matcher.match(testDescriptor, *descriptorIt, tempMatches);
for(int i = 0; i < testDescriptor.rows && i < (*descriptorIt).rows; ++i)
{
double dist = tempMatches[i].distance;
if(dist < min_dist)
{
min_dist = dist;
}
}
for(int i = 0; i < testDescriptor.rows && i < (*descriptorIt).rows; ++i)
{
if(tempMatches[i].distance <= max(2 * min_dist, 0.02))
{
temp_good_matches.push_back(tempMatches[i]);
++tempGoodMatchesCtr;
}
}
if(tempGoodMatchesCtr > goodMatchesCtr)
{
goodMatchesCtr = tempGoodMatchesCtr;
matches = tempMatches;
good_matches = temp_good_matches;
ctr = tempCtr;
}
}
// Displaying the test image alogside the best matching training image
Mat img_matches;
drawMatches(testImage, testKeypoints, trainingImages[ctr], keypoints[ctr], good_matches, img_matches, Scalar ::all(-1), Scalar ::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
for( int i = 0; i < (int)good_matches.size(); ++i )
{
printf( "-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx );
}
imshow("Good Matches", img_matches);
waitKey(0);
cout << "Executed!" << '\n';
return 0;
}
I write these programs on the gedit text editor and execute these programs on Ubuntu 12.04 with OpenCV 2.4.9.
EDIT: Basically I want a way to convert the below given lines of SIFT-PCA code into SIFT-LDA
PCA pca(testDescriptor1, Mat(), CV_PCA_DATA_AS_ROW, percentage);
pca.PCA::project(testDescriptor1, testDescriptor2);
testDescriptor = pca.PCA::backProject(testDescriptor2);
I tried to substitue the PCA constructor by the LDA constuctor in the following way:
LDA lda(testDescriptor, Mat());
lda.LDA::project(testDescriptor);
But I got the above mentioned error. My guess is that I am passing incorrect arguments to the LDA constructor. I have already gone through the documentation of LDA class given here, but had no luck in finding my mistake.
Any help regarding the above problem will be appreciated.
Thanks in advance!
I'm using OpenCV master branch (3.0.0. dev) with CUDA on Ubuntu 12.04, and trying to compile the following opencv with gpu code:
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/gpu/gpu.hpp"
using namespace cv;
int main (int argc, char* argv[])
{
try
{
cv::Mat src_host = cv::imread("file.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::gpu::GpuMat dst, src;
src.upload(src_host);
cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY);
cv::Mat result_host = dst;
cv::imshow("Result", result_host);
cv::waitKey();
}
catch(const cv::Exception& ex)
{
std::cout << "Error: " << ex.what() << std::endl;
}
return 0;
}
The compiling command is:
g++ testgpu.cpp -o test `pkg-config --cflags --libs opencv` -lopencv_gpu
It has the following compiling errors:
testgpu.cpp: In function ‘int main(int, char**)’:
testgpu.cpp:13:51: error: ‘CV_LOAD_IMAGE_GRAYSCALE’ was not declared in this scope
cv::Mat src_host = cv::imread("file.png", CV_LOAD_IMAGE_GRAYSCALE);
^
testgpu.cpp:17:52: error: ‘CV_THRESH_BINARY’ was not declared in this scope
cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY);
^
testgpu.cpp:19:31: error: conversion from ‘cv::gpu::GpuMat’ to non-scalar type ‘cv::Mat’ requested
cv::Mat result_host = dst;
^
It is something wrong with the installation of OpenCV, or the API change in Opencv 3.0.0?
The gpu module was redesigned in OpenCV 3.0. It was splitted onto several modules, it was renamed to cuda and gpu:: namespace was renamed to cuda::. The correct code for OpenCV 3.0:
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.hpp"
using namespace cv;
int main (int argc, char* argv[])
{
try
{
cv::Mat src_host = cv::imread("file.png", cv::IMREAD_GRAYSCALE);
cv::cuda::GpuMat dst, src;
src.upload(src_host);
cv::cuda::threshold(src, dst, 128.0, 255.0, cv::THRESH_BINARY);
cv::Mat result_host(dst);
cv::imshow("Result", result_host);
cv::waitKey();
}
catch(const cv::Exception& ex)
{
std::cout << "Error: " << ex.what() << std::endl;
}
return 0;
}
Ah, they've been playing with the constants in master. Expect the CV_* prefix removed almost anywhere ( except the types, CV_8U and such are still alive).
So it's cv::THRESH_BINARY, cv::LOAD_IMAGE_GRAYSCALE, but .... cv::COLOR_BGR2GRAY (you didn't use it now, but i'll spare you the searching ;) )
Sorry, I've no experience with GPU stuff, so i can't solve the last riddle there.
I am stuck with the problem while implementing chamfer matching program in OpenCV
https:// code.ros.org/trac/opencv/browser/trunk/opencv/samples/cpp/chamfer.cpp?rev=4194
Following is the code it is reading
template image
and test image
, I am using VS 2008 and OpenCV2.4.6
#include "stdafx.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
IplImage *src;
src = cvLoadImage("C:\\Users\\JOSHI\\Desktop\\Images\\logo_in_clutter.png",1);
Mat img=cvarrToMat(src);
imshow("Mat",img);
src = cvLoadImage("C:\\Users\\JOSHI\\Desktop\\Images\\logo.png",1);
Mat tpl=cvarrToMat(src);
imshow("Mat",tpl);
Mat cimg;
// if the image and the template are not edge maps but normal grayscale images,
// you might want to uncomment the lines below to produce the maps. You can also
// run Sobel instead of Canny.
Canny(img, img, 5, 50, 3);
Canny(tpl, tpl, 5, 50, 3);
vector<vector<Point> > results;
vector<float> costs;
int best = chamerMatching( img, tpl, results, costs );
if( best < 0 )
{
cout << "not found;\n";
return 0;
}
size_t i, n = results[best].size();
for( i = 0; i < n; i++ )
{
Point pt = results[best][i];
if( pt.inside(Rect(0, 0, cimg.cols, cimg.rows)) )
cimg.at<Vec3b>(pt) = Vec3b(0, 255, 0);
}
imshow("result", cimg);
waitKey();
return 0;
}
this is the error image
can you suggest me why I am getting this error as I am new to OpenCV and Image Processing
I had same problem. Solution: http://code.opencv.org/issues/3603
You need to download opencv from source, open the chamfermatching.cpp and comment line:
~Matching()
{
for (size_t i = 0; i<templates.size(); i++) {
//delete templates[i];
}
}
Then you need to rebuild opencv. After this it should work.