How to set 'nmixures' and 'bShadowDetection' values in 'BackgroundSubtractorMOG2'? - c++

Please have a look at the following code
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
using namespace cv;
using namespace std;
Mat frame,back,fore;
int main()
{
VideoCapture cam;
BackgroundSubtractorMOG2 bgs(0,0,false);
vector<vector<Point>>contours;
bgs.setInt("nmixtures",3);
cam.open(0);
if(!cam.isOpened())
{
cout << "Cam not Found";
return -1;
}
namedWindow("Frame");
while(true)
{
cam>>frame;
imshow("Frame",frame);
if(waitKey(30)>=0)
{
break;
}
}
}
I am trying to set the value of nmixures of BackgroundSubtractorMOG2 into 3 and bShadowDetection of BackgroundSubtractorMOG2 into false.
However, as with OpenCV 2.4.5, these values are set to private, so I can't acess them directly. I managed to set the value of bShadowDetection via the constructor (Eventhough I dnt know what other 2 params are), and I couldn't find a way to set the nmixers. I don't know whether The way I set the nmixures is correct or not,because in the article I read, the writer says "Set them via constructors in case of opencv 2.4"
Can you please tell me how to set those 2 values?

In OpenCV 2.4.8.:
bgs.set("nmixtures", 3);
bgs.set("detectShadows", false);

In your case, you have to write:
BackgroundSubtractorMOG2 bgs;
bgs.setInt("nmixtures", 3);
bgs.setBool("detectShadows", false);

Related

Is this a memory issue with DNN_BACKEND_CUDA and DNN_FRONTEND_CUDA?

I have the following code:
#include <iostream>
#include <opencv2/dnn_superres.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <filesystem>
#include <thread>
#include <future>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/core/cuda.hpp>
#include <iostream>
using namespace std;
using namespace cv;
using namespace cuda;
using namespace dnn;
using namespace dnn_superres;
int upsample_and_save(DnnSuperResImpl sr,
std::filesystem::path file_path,
std::filesystem::path save_dir) {
std::cout<<"We are inside of upsample_and_save!" ;
Mat img = cv::imread(file_path.string()); //Read image
std::cout<<"We are inside of upsample_and_save and read the image" ;
Mat img_new ; //Container to store upsampled image
std::cout<<"We are inside of upsample_and_save and created img_new" ;
sr.upsample(img, img_new); //Upsample
std::cout<<"We upsampled" ;
cv::imwrite((save_dir / file_path.filename()).string(), img_new); //Save upscaled image
std::cout<<"We wrote the image!" ;
std::cout<< (save_dir / file_path.filename()).string();
return 0;
}
int main() {
// Parameters
string original_path = "C:/Users/Administrator/Desktop/Upscale/original"; //Path to folder containing original files
std::filesystem::path upscaled_path = "C:/Users/Administrator/Desktop/Upscale/upscaled"; //Folder to save upscaled images
std::vector<std::string> models {"lapsrn", "fsrcnn"};
std::vector<std::string> model_weights {"LapSRN_x8.pb", "FSRCNN_x2.pb"};
std::vector<int> scale_factors {8,2};
string model_dir = "C:/Users/Administrator/Desktop/Upscale/models/";
int model_choice = 1; //CHOOSE MODEL HERE (index in vector starting from 0)
std::vector<std::string> allowed {".jpg",".png"}; //Allowed image types
string model = models[model_choice]; //Model for dnn_superres
int scale_factor = scale_factors[model_choice]; //Scale factor
string model_path = model_dir + model_weights[model_choice]; //Model weights
DnnSuperResImpl sr; //Module instance
sr.readModel(model_path); //Read model weights
sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
sr.setModel(model, scale_factor); //Set model and scale
std::cout<<"We set up OK!";
for (const auto &file : std::filesystem::directory_iterator(original_path)) {
std::cout<<"We are inside of the for loop!";
if (std::count(allowed.begin(), allowed.end(), file.path().extension())) {
upsample_and_save(sr, file.path(), upscaled_path);
std::cout<< "We hit upsample in the for loop!";
} else {
std::cout<<"The if statement has failed!";
}
std::cout<< "out of the loop";
return 0;
}
}
The issue I am having:
If I set the model to FSRCNN_x2.pb by adjusting model_choice to 1, the code works great! This model upscales an image by 2x. However, if I select LapSRN_x8.pb, the code will produce the following output:
PS C:\Users\Administrator\Desktop\Upscale\build\Release> ."C:/Users/Administrator/Desktop/Upscale/build/Release/upscale.exe"
We set up OK! We are inside of the for loop! We hit upsample in the for loop! We are inside of upsample_and_save! We are inside of upsample_and_save and read the image! We are inside of upsample_and_save and created img_new
PS C:\Users\Administrator\Desktop\Upscale\build\Release>
The code seems to hit the sr.upsample(img,img_new) and then completely crash!
I have attempted to fix this by commenting out
sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
And after doing so, it appears that the code works fine. Does anyone know why this is happening?

Done building project "Project.vcxproj" -- FAILED

I wrote some lines of code to simply read and write an image and it was working a few days ago, but now Visual Studio gives these errors: "1>Done building project "Lab1_PI.vcxproj" -- FAILED." and it says it was "unable to start the program" and that the system cannot find the file specified.
I also tried to add add _CRT_SECURE_NO_DEPRECATE and _CRT_SECURE_NO_WARNINGS via right-click project->C/C+±>Preprocessor->Preprocessor Definitions, but nothing changed.
Also, here's my code, but it is correct since it was working a few days ago:
#include <iostream>
#include <string>
#include "opencv2\core.hpp"
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\imgproc\imgproc.hpp"
using namespace cv;
using namespace std;
int main(int arc, const char** argv) {
string imgPath = argv[1];
string img2Path = argv[2];
cv::Mat img = imread(imgPath);
if (!img.data) {
cout << "error:no image" << endl;
return -1;
}
imshow("flower image (color)", img);
Mat img2;
cvtColor(img, img2, COLOR_RGB2GRAY);
imwrite(img2Path, img2);
imshow("flower image (grey)", img2);
waitKey(0);
}
I would be really grateful if someone could help me fix this problem because it stops me from using Visual Studio and I really need it for a project!

error: no matching function for call to 'FaceDetector::FaceDetector(std::__cxx11::string)'

I am new to C++ and i am getting error like
error: no matching function for call to 'FaceDetector::FaceDetector(std::__cxx11::string)'
FaceDetector fd(string(DEFAULT_CASCADE_PATH));
and i am attaching my code and error log how to fix this please guide me
#define DEFAULT_CASCADE_PATH "cascades/haarcascade_frontalface_default.xml"
#define ORIGINALS_LIST "obama_raw/list"
#define OUTPUT_DIR "obama_faces"
#define OUTPUT_LIST "list"
#define FACE_SIZE Size(150,150)
#include <cstdlib>
#include <fstream>
#include "cv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "FaceDetector.h"
using namespace std;
using namespace cv;
void read_input_list(const string &list_path, vector<Mat> &images) {
ifstream file(list_path.c_str());
string path;
while (getline(file, path)) {
images.push_back(imread(path));
}
}
int main(int argc, char** argv) {
FaceDetector fd(string(DEFAULT_CASCADE_PATH));
vector<Mat> raw_faces;
ofstream out_list(format("%s/%s", OUTPUT_DIR, OUTPUT_LIST).c_str());
read_input_list(string(ORIGINALS_LIST), raw_faces);
int img_c = 0; //images counter
//now detect the faces in each of the raw images:
for (vector<Mat>::const_iterator raw_img = raw_faces.begin() ; raw_img != raw_faces.end() ; raw_img++){
vector<Rect> faces;
//detect faces in the image (there should be only one):
fd.findFacesInImage(*raw_img, faces);
//cut each face and write to disk:
for (vector<Rect>::const_iterator face = faces.begin() ; face != faces.end() ; face++){
int edge_size = max(face->width, face->height);
Rect square(face->x, face->y, edge_size, edge_size);
Mat face_img = (*raw_img)(square);
//resize:
resize(face_img, face_img, FACE_SIZE);
//write to disk:
string face_path = format("%s/%d.jpg", OUTPUT_DIR, img_c++);
imwrite(face_path,face_img);
out_list << face_path << endl;
}
}
out_list.close();
return 0;
}
and i am attaching my error log.Please can any one help.
Thanks in advance
Error : https://i.stack.imgur.com/RZXXK.jpg
From GCC 5, A new ABI is enabled by default. In that new ABI, std::__cxx11 namesapce was introduced.
According to your error message, It seems that your program and OpenCV library you want to link with were build with different GCC version, which made incompatible binary.
For more information, you can read the following page:
https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html

OpenCV VideoWriter does not open file

The following code fails to open a VideoWriter object:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
VideoWriter oVideo;
oVideo.open ("381.avi", -1, 30, Size(640,480), true);
if (!oVideo.isOpened()) {
cout << "Could not open the output video for write" << endl;
return -1;
}
return 0;
}
I'm running OpenCV 2.4.9 pre-built with Code::Blocks on Ubuntu 12.04. I've written a number of images using imwrite() on the same location without issue, so I doubt it has to do with permissions. Also I tried CV_FOURCC('X','V','I','D') which did not work.
What am I missing here?
Any help is greatly appreciated.
I reinstalled OpenCV using this amazing script: https://help.ubuntu.com/community/OpenCV
Solved.
Make sure specific codec is installed in your machine.

warning: Could not find codec parameters (../../modules/highgui/src/cap_ffmpeg_impl.hpp:540)

I am trying to display the video feed from IP camera getting the following error
warning: Could not find codec parameters
(../../modules/highgui/src/cap_ffmpeg_impl.hpp:540)
Here's the code for the same.
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int, char**)
{
VideoCapture vcap;
Mat image;
// This works on a D-Link CDS-932L
const string videoStreamAddress = "http://admin:admin123#172.41.20.55:80/? action=stream?dummy=param.mjpg";//From mjpeg streamer
//const string videoStreamAddress = "http://192.168.1.13:8080/videofeed? dummy=param.mjpg"; // Streaming from android using ip-cam
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
cout << "Error opening video stream or file" << std::endl;
return -1;
}
for(;;) {
if(!vcap.read(image)) {
cout << "No frame" << std::endl;
waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
First i got different error so I installed K-Lite codec. Now I am getting this error.
Can some one please tell me what is the error related to.
I have gone through many post from stackoverflow and opencv also but could manage to get a satisfactory answer.
Please help me.
Thanks in advance.
I was able to Solve the problem with the following code.
#include <stdio.h>
#include <opencv2/opencv.hpp>
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:password#ipOfCamera/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
/*if(img){
cvSaveImage("C:/opencv.jpg",img);
}*/
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
Would be good if it helps someone like me.
Also Thanks #karlphillip for giving your time.
Warnings are not errors! Relax.
In this case FFmpeg is complaining and not OpenCV. The reason is probably because the mjpg format that is specified on the URL doesn't really require an actual codec.