I have this code that basically does a "dumb" background subtraction on two frames.
void FrameDifferenceBGS::operator()(cv::InputArray _image, cv::OutputArray _fgmask, double learningRate)
{
cv::Mat img_input = _image.getMat();
if(img_input.empty())
return;
_fgmask.create(img_input.size(), CV_8U);
cv::Mat img_foreground = _fgmask.getMat();
if(img_input_prev.empty())
{
img_input.copyTo(img_input_prev);
return;
}
cv::absdiff(img_input_prev, img_input, img_foreground);
if(img_foreground.channels() == 3)
cv::cvtColor(img_foreground, img_foreground, CV_BGR2GRAY);
if(enableThreshold)
cv::threshold(img_foreground, img_foreground, threshold, 255, cv::THRESH_BINARY);
if(showOutput)
cv::imshow("Frame Difference", img_foreground);
img_input.copyTo(img_input_prev);
img_foreground.copyTo(_fgmask);
firstTime = false;
}
If I don't add img_foreground.copyTo(_fgmask) in the end, the output array isn't updated with the result of img_foreground, resulting on a black image when this is called.
What am I doing wrong / should be doing here?
I reviewed your code again. It looks like you are creating new object for _fgmask.
_fgmask.create(img_input.size(), CV_8U);
I think this is why you have the problem. Because of this reference in the argument is different from the one after this statement. Why don't you call the line before calling the function.
fix
change _fgmask.create(img_input.size(), CV_8U); to _fgmask.create(img_input.size(), CV_8UC3); or _fgmask.create(img_input.size(), img_input.type());
why
this is because cv::absdiff(img_input_prev, img_input, img_foreground); recreate a new array everytime internally. and it does update the img_foreground structure but after the allocation, the memory address data inside _fgmask fail to change since the headers are passed by value.
you can seemlingly fix this(but still incurs creation cost) by doing cv::Mat& img_foreground = _fgmask.getMatRef();
and that is because CV_8U is not the same as CV_8UC3 and therefore the check # Mat::create() in mat.hpp always end up allocating a new array due to type difference
opinion
i think...maybe use Mat instead?
#include "opencv2/opencv.hpp"
using namespace cv;
class FrameDifferenceBGS
{
public:
Mat prev;
Mat diff;
bool enableThreshold;
bool showOutput;
bool firstTime;
uchar threshold;
FrameDifferenceBGS():firstTime(false),enableThreshold(false),showOutput(false),threshold(0)
{
}
void FrameDifferenceBGS::operator()(cv::Mat& _in, cv::Mat &_fg, double _lr)
{
if(_in.empty())
return;
if(prev.empty())
{
prev=_in.clone();
_fg=cv::Mat::zeros(_in.size(),CV_8UC1);
return;
}
cv::absdiff(prev, _in, diff);
if(diff.channels() == 3)
cv::cvtColor(diff, _fg, CV_BGR2GRAY);
else
_fg=diff;
if(enableThreshold)
cv::threshold(_fg, _fg, threshold, 255, cv::THRESH_BINARY);
if(showOutput)
cv::imshow("Frame Difference", _fg);
prev=_in.clone();
firstTime = false;
}
};
int main()
{
VideoCapture cap(0);
FrameDifferenceBGS bgs;
Mat frame,fg;
for(;;)
{
cap >> frame;
bgs(frame,fg,0);
imshow("frame", frame);
imshow("fg", fg);
if(waitKey(1) ==27) exit(0);
}
return 0;
}
edit 2(modified original)
#include "opencv2/opencv.hpp"
class FrameDifferenceBGS
{
public:
cv::Mat img_input_prev;
cv::Mat diff;
cv::Mat img_foreground;//put this in class in stead of inside the function
bool enableThreshold;
bool showOutput;
bool firstTime;
uchar threshold;
FrameDifferenceBGS():firstTime(false),enableThreshold(false),showOutput(false),threshold(0)
{
}
void FrameDifferenceBGS::operator()(cv::InputArray _image, cv::OutputArray _fgmask, double learningRate)
{
cv::Mat img_input = _image.getMat();
if(img_input.empty())
return;
if(_fgmask.empty())
_fgmask.create(img_input.size(), CV_8UC1);
if(img_input_prev.empty())
{
img_input.copyTo(img_input_prev);
return;
}
cv::absdiff(img_input_prev, img_input, img_foreground);
if(img_foreground.channels() == 3)
cv::cvtColor(img_foreground, _fgmask, CV_BGR2GRAY);
if(enableThreshold)
cv::threshold(img_foreground, img_foreground, threshold, 255, cv::THRESH_BINARY);
if(showOutput)
cv::imshow("Frame Difference", img_foreground);
img_input.copyTo(img_input_prev);
//img_foreground.copyTo(_fgmask);
firstTime = false;
}
};
int main()
{
cv::VideoCapture cap(0);
FrameDifferenceBGS bgs;
cv::Mat frame,fg;
for(;;)
{
cap >> frame;
bgs(frame,fg,0);
cv::imshow("frame", frame);
cv::imshow("fg", fg);
if(cv::waitKey(1) ==27) exit(0);
}
return 0;
}
Related
I have created a simple class to detect corners using
harris algorithm
. it is working but when I change the threshold value using trackbar and when the value is getting low (below 100) then the process is stopped.
this is my sample code.
my header file
class CornerCapturer{
struct configValues
{
int block;
int k_size;
int thre;
double k;
configValues() :block(2), k_size(3), thre(100), k(0.04){}
};
public:
static configValues conf;
void captureCorners();
static void captevent(int, void*);
Mat captureCornerPoints(int thresh, int block, int k_size, double k, Mat frame);
};
my Cpp file
void CaptureBall::detectCorners(){
CornerCapturer capt;
VideoCapture cap = capture.captureVideo();
cap.read(frame);
capt.captureCorners();
for (;;){
cap.read(frame);
capt.captevent(0, 0);
waitKey(5);
}
}
void CornerCapturer::captureCorners(){
int *t = &CornerCapturer::conf.thre;
namedWindow("Open", CV_WINDOW_AUTOSIZE);
captevent(0, 0);
createTrackbar("Thresh", "Open", t, 255, CornerCapturer::captevent);
}
void CornerCapturer::captevent(int, void*){
Mat res;
CornerCapturer cap;
res = cap.captureCornerPoints(CornerCapturer::conf.thre, CornerCapturer::conf.block, CornerCapturer::conf.k_size, CornerCapturer::conf.k, frame);
imshow("Open", res);
}
Mat CornerCapturer::captureCornerPoints(int thresh, int block, int k_size, double k, Mat f){
Mat gray, corner_detected, cnv_normal,copy;
copy = f;
cvtColor(copy, gray, COLOR_RGB2GRAY); // convert to gray image
cornerHarris(gray, corner_detected, block, k_size, k, BORDER_DEFAULT); // detect cornet points
normalize(corner_detected, cnv_normal, 0, 255, NORM_MINMAX, CV_32FC1, Mat()); // normalize image
for (int j = 0; j < cnv_normal.rows; j++)
{
for (int i = 0; i < cnv_normal.cols; i++)
{
if ((int)cnv_normal.at<float>(j, i) > thresh)
{
circle(copy, Point(i, j), 8, Scalar(120), 2, 8, 0); // put points
}
}
}
return copy;
}
i used OpenCV library for track corners
I have written a program in opencv(c++) to manipulate camera property. I am trying to blur my camera display using "track bar". The code is working but in certain condition. It works, when i change the position of "track bar" using mouse click. But if i tried to slide the track bar it gives me an error as mention below.
Here is my code
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat image, image_blurred;
int slider=5;
float sigma=0.3 *((slider - 1)*0.5 - 1) +0.8;
void on_Trackbar(int,void *)
{
int k_size = max(1,slider);
//k_size = k_size%2 == 0 ? k_size+1 : k_size;
setTrackbarPos("kernel","Blur window",3);
sigma=0.3 *((slider - 1)*0.5 - 1) +0.8;
GaussianBlur(image,image_blurred,Size(3,3),sigma);
}
int main()
{
Mat img;
VideoCapture cap(0);
if(!cap.isOpened())
{
cout<<"Camera is not successfully opened"<<endl;
return -1;
}
namedWindow("original image",CV_WINDOW_AUTOSIZE);
namedWindow("Blur Image",CV_WINDOW_AUTOSIZE);
while(!char(waitKey(30)=='q') && cap.isOpened())
{
cap>>img;
GaussianBlur(img,image_blurred,Size(slider,slider),sigma);
createTrackbar("kernel","Blur Image",&slider,21,on_Trackbar);
imshow("Blur Image",image_blurred);
imshow("original image",img);
}
destroyAllWindows();
return 0;
}
Please give your valuable views. Thanks in advance!!.
In the while loop, you're passing an invalid value to GaussianBlur, since slider can also be an even number.
You can correct this introducing a new variable int kernel_size = 2*slider+1. slider now is the radius of the kernel, and kernel_size is guaranteed to be odd.
Also you don't need to call GaussianBlur in the callback function, since it's already called in the main loop. The only goal of the callback is to update the values of kernel_size and sigma.
This code will work as expected:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat image, image_blurred;
int slider = 0;
int kernel_size = 3;
float sigma = 0.3 *((kernel_size - 1)*0.5 - 1) + 0.8;
void on_Trackbar(int, void *)
{
kernel_size = 2 * slider + 1;
sigma = 0.3 *((kernel_size - 1)*0.5 - 1) + 0.8;
}
int main()
{
Mat img;
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "Camera is not successfully opened" << endl;
return -1;
}
namedWindow("original image", CV_WINDOW_AUTOSIZE);
namedWindow("Blur Image", CV_WINDOW_AUTOSIZE);
createTrackbar("kernel", "Blur Image", &slider, 21, on_Trackbar);
while (!char(waitKey(30) == 'q') && cap.isOpened())
{
cap >> img;
GaussianBlur(img, image_blurred, Size(kernel_size, kernel_size), sigma);
imshow("Blur Image", image_blurred);
imshow("original image", img);
}
destroyAllWindows();
return 0;
}
Seems that the findContours function has been returning some assertion fails with Visual Studios C++ 2012. I've made sure that all my include directories were fine.
void track (Mat input_video, Mat &output_video)
{
Mat temp;
input_video.copyTo(temp);
vector<vector<cv::Point> > contours;
vector<Vec4i> hierarchy;
findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
//Only search through the most external layer.
for (int i=0; i>=0; i=hierarchy[i][0])
{
Moments moment = moments((Mat) contours[i]);
double area= moment.m00;
double xmc= moment.m10;
double ymc= moment.m01;
double x= xmc/area;
double y= ymc/area;
circle(output_video, Point(x,y), 3, Scalar(0,255,255));
}
}
EDIT:
The rest of my code if you may need it:
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
//This function threshold the HSV image and create a binary image
Mat GetThresholdedImage(Mat imgHSV, int huemin, int satmin, int valmin, int huemax, int satmax, int valmax)
{
//Size s= imgHSV->size();
Mat imgThresh(imgHSV.size().height, imgHSV.size().width, CV_8U);
//returns matrix that contains all values within the given HSV range.
inRange(imgHSV, Scalar(huemin,satmin,valmin), Scalar(huemax,satmax,valmax), imgThresh);
return imgThresh;
}
Mat morph(Mat imgThresh)
{
Mat erode_element= getStructuringElement(MORPH_RECT, Size(3,3));
Mat dilate_element= getStructuringElement(MORPH_RECT, Size(8,8));
erode(imgThresh, imgThresh, erode_element);
erode(imgThresh, imgThresh, erode_element);
dilate(imgThresh, imgThresh, dilate_element);
return imgThresh;
}
void track (Mat input_video, Mat &output_video)
{
Mat temp;
input_video.copyTo(temp);
vector< vector<Point> > contours;
cerr<< contours.size();
vector<Vec4i> hierarchy;
findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
cerr<<contours.size();
//Only search through the most external layer.
for (int i=0; i>=0; i=hierarchy[i][0])
{
Moments moment = moments((Mat) contours[i]);
double area= moment.m00;
double xmc= moment.m10;
double ymc= moment.m01;
double x= xmc/area;
double y= ymc/area;
circle(output_video, Point(x,y), 3, Scalar(0,255,255));
}
}
int main()
{
VideoCapture capture(0);
if(!capture.isOpened()){
cerr<< "Capture failed";
return -1;
}
Mat frame;
namedWindow("Original");
namedWindow("Binary");
//Create slider for adjustments...
namedWindow("Adjustments");
int huemin= 0, satmin= 0, valmin= 0;
int huemax= 256, satmax= 256, valmax= 256;
createTrackbar("Min Hue", "Adjustments", &huemin, 256);
createTrackbar("Max Hue", "Adjustments", &huemax, 256);
createTrackbar("Min Saturation", "Adjustments", &satmin, 256);
createTrackbar("Max Saturation", "Adjustments", &satmax, 256);
createTrackbar("Min Value", "Adjustments", &valmin, 256);
createTrackbar("Max Value", "Adjustments", &valmax, 256);
//iterate through each frames of the video
while(true)
{
//Grabs each frame from video to be processed.
capture>> frame;
//Error checks and breaks if the grab failed.
if(!frame.data)
{
cerr<< "Failed to grab frame\n";
break;
}
//Apply a Gaussian Blur kernel.
//GaussianBlur(frame, frame, Size(3,3), 3, 3, 4);
Mat imgHSV(frame.size(), CV_8UC3);
cvtColor(frame, imgHSV, CV_BGR2HSV, 0); //Change the color format from BGR to HSV
Mat imgThresh = GetThresholdedImage(imgHSV, huemin, satmin, valmin, huemax, satmax, valmax);
//GaussianBlur(imgThresh, imgThresh, Size(5,5), 3, 3, 4); //smooth the binary image using Gaussian kernel
imgThresh= morph(imgThresh);
track(imgThresh, frame);
imshow("Binary", imgThresh);
imshow("Original", frame);
int key = waitKey(30);
//If 'ESC' is pressed, break the loop
if(key==27 ) break;
}
destroyAllWindows();
//cvReleaseCapture(&capture);
return 0;
}
Eugene, I encountered the same problem. try to add "cv::imshow("im", output_video);"
as mentioned in - OpenCV findContours causes Debug Assertion Failed at return
I am trying to overlay an image over the video capture of my program with OpenCV but I am having trouble getting it to work. I set the a region of interest in the original frame taken from the webcam in the form of a rectangle. Then i copy it to the original frame. However it never shows up on the new frame captured by the webcam. I tested it and the image is loading correctly but it is not being copied to the new frame for some reason.
Code Below in C++:
#include<opencv2/core/core.hpp>
#include<opencv2/contrib/contrib.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
#include<vector>
using namespace std;
using namespace cv;
int main(){
VideoCapture cap;
cap.open(0);
if(!cap.isOpened()){
cerr << "Error opening the webcam!" << endl;
return -1;
}
for(;;){
Mat frame;
cap>>frame;
Mat newFrame;
frame.copyTo(newFrame);
Mat image = imread("C:\\User\\Desktop\\images\\image.png");
int cx = (newFrame.cols - 70) / 2;
if (image.data) {
// Get a BGR version of the face, since the output is BGR color
Mat srcBGR = Mat(face.size(), CV_8UC3);
cvtColor(image, srcBGR, CV_GRAY2BGR);
// Get the destination ROI (and make sure it is within the image)
Rect dstRC = Rect(cx, newFrame.rows/2, 70, 70);
Mat dstROI = newFrame(dstRC);
// Copy the pixels from src to dst.
srcBGR.copyTo(dstROI);
}
imshow("frame", newFrame);
char key = (char) waitKey(30);
// Exit this loop on escape:
if(key == 27)
break;
}
return 0;
}
Any suggestions or help would be appreciated. Thanks.
You converted image to BGR by using not converted one:
change this: image.copyTo(dstROI); to this srcBGR.copyTo(dstROI);
#include<opencv2/core/core.hpp>
#include<opencv2/contrib/contrib.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
#include<vector>
using namespace std;
using namespace cv;
int main(){
VideoCapture cap;
cap.open(0);
if(!cap.isOpened()){
cerr << "Error opening the webcam!" << endl;
return -1;
}
Mat image = imread("D:\\ImagesForTest\\Lena.jpg",0);
cv::resize(image,image,Size(70,70));
Mat frame;
for(;;){
cap>>frame;
Mat newFrame=frame.clone();
int cx = (newFrame.cols - 70) / 2;
if (!image.empty()) {
// Get a BGR version of the face, since the output is BGR color
Mat srcBGR = Mat(image.size(), CV_8UC3);
cvtColor(image, srcBGR, CV_GRAY2BGR);
// Get the destination ROI (and make sure it is within the image)
Rect dstRC = Rect(cx, newFrame.rows/2, 70, 70);
Mat dstROI = newFrame(dstRC);
// Copy the pixels from src to dst.
srcBGR.copyTo(dstROI);
}
imshow("frame", newFrame);
char key = (char) waitKey(30);
// Exit this loop on escape:
if(key == 27)
break;
}
return 0;
}
I wrote a short routine in openCV and C++ to track objects with a webcam. The webcam formulation was speedy with no lag, but before leaving work for the weekend, I recorded a typical sequence to use as a test template while I work until Monday. This and the corresponding change in code somehow make the video play back in really slow motion. Here is the code, opening "Test.avi", ~20 seconds long instead of running a constant stream off of the webcam:
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
Mat drawBoundingBoxes (Mat canvasImage, vector<vector<Point>> contours);
int main(int argc, char** argv[])
{
Mat frame;
Mat back;
Mat fGround;
BackgroundSubtractorMOG2 bGround;
bGround.nmixtures = 3;
//bGround.nShadowDetection = 0;
bGround.fTau = .5;
VideoCapture cap;
cap.open("Test.avi");
if (!cap.isOpened())
{
cout << "Can't open video" << endl;
return -1;
}
vector<vector<Point>> contours;
namedWindow("video", CV_WINDOW_AUTOSIZE);
while (true)
{
static int count = 1;
cap >> frame;
if (frame.empty())
break;
bGround.operator()(frame, fGround);
bGround.getBackgroundImage(back);
erode(fGround, fGround, Mat(), Point(-1,-1), 2, BORDER_DEFAULT);
dilate(fGround, fGround, Mat(), Point(-1,-1), 10, BORDER_DEFAULT);
if (count > 50)
{
findContours(fGround, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
drawContours(frame, contours, -1, Scalar(239,255,0), 2);
drawBoundingBoxes(frame, contours);
}
imshow("video", frame);
if(waitKey(30) >= 0)
break;
count++;
}
return 0;
}
Mat drawBoundingBoxes (Mat canvasImage, vector<vector<Point>> contours)
{
vector<Rect> boundRect(contours.size());
for (int i=0; i<contours.size(); i++)
{
boundRect[i] = boundingRect(contours[i]);
rectangle(canvasImage, boundRect[i], Scalar(153,0,76), 2, 8, 0);
}
return canvasImage;
}
Any ideas? Memory Leak somewhere? Thanks,
-Tony
I believe your recorded video has a higher framerate than that your PC can process real time. It's not a problem with a webcam as it just drops the frames. You could try to decrease the delay in the waitKey() procedure and see if that helps.