how to draw curve on control points using opencv - opencv

I want to draw curve on control points so that I can move the curve to change the colours , below is the code , getting help from a very well explained answer
const int N=5; // number of control points (must be >= 4)
float ctrl[N]= // control points y values initiated with linear function y=x
{ // x value is index*1.0/(N-1)
0.00,
0.25,
0.50,
0.75,
1.00,
};
float correction(float col,float *ctrl,int n)
{
float di=1.0/float(n-1);
int i0,i1,i2,i3;
float t,tt,ttt;
float a0,a1,a2,a3,d1,d2;
// find start control point
col*=float(n-1);
i1=col; col-=i1;
i0=i1-1;
i2=i1+1; if (i2>=n) i2=n-1;
i3=i1+2;
// compute interpolation coefficients
if (i0>=0) d1=0.5*(ctrl[i2]-ctrl[i0]); else d1=ctrl[i2]-ctrl[i1];
if (i3< n) d2=0.5*(ctrl[i3]-ctrl[i1]); else d2=ctrl[i2]-ctrl[i1];
a0=ctrl[i1];
a1=d1;
a2=(3.0*(ctrl[i2]-ctrl[i1]))-(2.0*d1)-d2;
a3=d1+d2+(2.0*(-ctrl[i2]+ctrl[i1]));
// now interpolate new colro intensity
t=col; tt=t*t; ttt=tt*t;
t=a0+(a1*t)+(a2*tt)+(a3*ttt);
return t;
}
int main (int argc, const char** argv)
{
Mat input = imread ("E:\\img2.jpg");
Mat input1 = input;
for(int i=0 ; i<input1.rows ; i++)
{
for (int p=0;p<input1.cols;p++)
{
input1.at<cv::Vec3b>(i,p)[0] = 255*correction(input1.at<cv::Vec3b>(i,p)[0]/255.0,ctrl,N); //B
input1.at<cv::Vec3b>(i,p)[1] = 255*correction(input1.at<cv::Vec3b>(i,p)[1]/255.0,ctrl,N); //G
input1.at<cv::Vec3b>(i,p)[2] = 255*correction(input1.at<cv::Vec3b>(i,p)[2]/255.0,ctrl,N); //R
}
}
imshow("image" , input);
waitKey();
}
But the required output is like the curve the program is working , but the curves are not drawing on my screen like below , how to draw them using opencv or other approach So that these lines can play the role of their specific colour in image and with their values , like below right one is the orignal image and left one is the result of changing values through cuves , below curves are the control points per B,G,R

This code sketch allows you to edit spline with mouse it uses the files from this link (attach to your project: overhauser.cpp overhauser.hpp and vec3.hpp):
Left mouse button adds/moves a point, right removes.
#include <iostream>
#include <vector>
#include <stdio.h>
#include <functional>
#include <algorithm>
#include <numeric>
#include <cstddef>
#include "opencv2/opencv.hpp"
#include <iostream>
#include <fstream>
#include "overhauser.hpp"
using namespace std;
using namespace cv;
Mat result;
Mat Img;
int current_color=0;
vector<cv::Point2f> pts_red;
vector<cv::Point2f> pts_green;
vector<cv::Point2f> pts_blue;
Mat curvesImg;
int selectedPt=-1;
CRSpline* spline_red = 0;
CRSpline* spline_green = 0;
CRSpline* spline_blue = 0;
unsigned char LUT_RED[256];
unsigned char LUT_GREEN[256];
unsigned char LUT_BLUE[256];
// comparison function:
bool mycomp (Point2f p1, Point2f p2)
{
return p1.x<p2.x;
}
float dist(Point2f p1,Point2f p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
int findNEarestPt(Point2f pt, float maxDist)
{
vector<Point2f> current_pts_set;
current_color=0;
if(pt.x>255 && pt.x<512)
{
current_color=1;
}
if(pt.x>=512)
{
current_color=2;
}
float ptx=pt.x;
switch(current_color)
{
case 0:
current_pts_set=pts_red;
break;
case 1:
current_pts_set=pts_green;
pt.x-=255;
break;
case 2:
current_pts_set=pts_blue;
pt.x-=511;
break;
}
float minDist=FLT_MAX;
int ind=-1;
for(int i=0;i<current_pts_set.size();++i)
{
float d=dist(pt,current_pts_set[i]);
if(minDist>d)
{
ind=i;
minDist=d;
}
}
if(minDist>maxDist)
{
ind=-1;
}
return ind;
}
float F(float t,float x, CRSpline* spline)
{
vec3 rv = spline->GetInterpolatedSplinePoint(t);
return x-rv.x;
}
float solveForX(float x,CRSpline* slpine)
{
float a=-1.0f,b=1.0,c,e=1e-2;
c=(a+b)/2;
while( (fabs(b-a)>e) && (F(c,x,slpine)!=0) )
{
if (F(a,x,slpine)*F(c,x,slpine)<0)
{
b=c;
}
else
{
a=c;
}
c=(a+b)/2;
}
return c;
}
int ind=-1;
void mouseHandler(int event, int x, int y, int flags, void* param)
{
Point2f m;
m.x=x;
m.y=y;
curvesImg=Scalar(0,0,0);
switch (event)
{
case cv::EVENT_RBUTTONDOWN:
ind=findNEarestPt(m,5);
if (ind==-1)
{
}else
{
switch(current_color)
{
case 0:
pts_red.erase(pts_red.begin()+ind);
break;
case 1:
pts_green.erase(pts_green.begin()+ind);
break;
case 2:
pts_blue.erase(pts_blue.begin()+ind);
break;
}
ind=-1;
}
break;
case cv::EVENT_LBUTTONDOWN:
ind=findNEarestPt(m,5);
if (ind==-1)
{
switch(current_color)
{
case 0:
pts_red.push_back(m);
selectedPt=pts_red.size()-1;
break;
case 1:
pts_green.push_back(Point2f(m.x-255.0,m.y));
selectedPt=pts_green.size()-1;
break;
case 2:
pts_blue.push_back(Point2f(m.x-511,m.y));
selectedPt=pts_blue.size()-1;
break;
}
}else
{
selectedPt=ind;
}
break;
case cv::EVENT_MOUSEMOVE:
if(ind!=-1)
{
switch(current_color)
{
case 0:
pts_red[selectedPt].x=m.x;
pts_red[selectedPt].y=m.y;
break;
case 1:
pts_green[selectedPt].x=m.x-255;
pts_green[selectedPt].y=m.y;
break;
case 2:
pts_blue[selectedPt].x=m.x-511;
pts_blue[selectedPt].y=m.y;
break;
}
}
break;
case cv::EVENT_LBUTTONUP:
ind=-1;
break;
}
std::sort(pts_red.begin(),pts_red.end(),mycomp);
if(pts_red.size()>0)
{
pts_red[pts_red.size()-1].x=255;
pts_red[0].x=0;
}
std::sort(pts_green.begin(),pts_green.end(),mycomp);
if(pts_green.size()>0)
{
pts_green[pts_green.size()-1].x=255;
pts_green[0].x=0;
}
std::sort(pts_blue.begin(),pts_blue.end(),mycomp);
if(pts_blue.size()>0)
{
pts_blue[pts_blue.size()-1].x=255;
pts_blue[0].x=0;
}
for(int i=0;i<pts_red.size();++i)
{
circle(curvesImg,pts_red[i],5,Scalar(0,0,255),-1,CV_AA);
}
for(int i=0;i<pts_green.size();++i)
{
circle(curvesImg,Point2f(pts_green[i].x+255,pts_green[i].y),5,Scalar(0,255,0),-1,CV_AA);
}
for(int i=0;i<pts_blue.size();++i)
{
circle(curvesImg,Point2f(pts_blue[i].x+511,pts_blue[i].y),5,Scalar(255,0,0),-1,CV_AA);
}
if (spline_red) {delete spline_red;}
spline_red = new CRSpline();
if (spline_green) {delete spline_green;}
spline_green = new CRSpline();
if (spline_blue) {delete spline_blue;}
spline_blue = new CRSpline();
for (int i=0;i<pts_red.size();++i)
{
vec3 v(pts_red[i].x,pts_red[i].y,0);
spline_red->AddSplinePoint(v);
}
for (int i=0;i<pts_green.size();++i)
{
vec3 v(pts_green[i].x,pts_green[i].y,0);
spline_green->AddSplinePoint(v);
}
for (int i=0;i<pts_blue.size();++i)
{
vec3 v(pts_blue[i].x,pts_blue[i].y,0);
spline_blue->AddSplinePoint(v);
}
vec3 rv_last(0,0,0);
if(pts_red.size()>2)
{
for(int i=0;i<256;++i)
{
float t=solveForX(i,spline_red);
vec3 rv = spline_red->GetInterpolatedSplinePoint(t);
if(rv.y>255){rv.y=255;}
if(rv.y<0){rv.y=0;}
unsigned char I=(unsigned char)(rv.y);
LUT_RED[i]=255-I;
if(i>0)
{
line(curvesImg,Point(rv.x,rv.y),Point(rv_last.x,rv_last.y),Scalar(0,0,255),1);
}
rv_last=rv;
}
}
rv_last=vec3(0,0,0);
if(pts_green.size()>2)
{
for(int i=0;i<256;++i)
{
float t=solveForX(i,spline_green);
vec3 rv = spline_green->GetInterpolatedSplinePoint(t);
if(rv.y>255){rv.y=255;}
if(rv.y<0){rv.y=0;}
unsigned char I=(unsigned char)(rv.y);
LUT_GREEN[i]=255-I;
if(i>0)
{
line(curvesImg,Point(rv.x+255,rv.y),Point(rv_last.x+255,rv_last.y),Scalar(0,255,0),1);
}
rv_last=rv;
}
}
rv_last=vec3(0,0,0);
if(pts_blue.size()>2)
{
for(int i=0;i<256;++i)
{
float t=solveForX(i,spline_blue);
vec3 rv = spline_blue->GetInterpolatedSplinePoint(t);
if(rv.y>255){rv.y=255;}
if(rv.y<0){rv.y=0;}
unsigned char I=(unsigned char)(rv.y);
LUT_BLUE[i]=255-I;
if(i>0)
{
line(curvesImg,Point(rv.x+511,rv.y),Point(rv_last.x+511,rv_last.y),Scalar(255,0,0),1);
}
rv_last=rv;
}
}
int cur_col=0;
if(m.x>255 && m.x<512)
{
cur_col=1;
}
if(m.x>=512)
{
cur_col=2;
}
Scalar col;
switch(cur_col)
{
case 0:
col=Scalar(0,0,255);
break;
case 1:
col=Scalar(0,255,0);
break;
case 2:
col=Scalar(255,0,0);
break;
}
line(curvesImg,Point(0,m.y),Point(curvesImg.cols,m.y),col,1);
line(curvesImg,Point(m.x,0),Point(m.x,curvesImg.rows),col,1);
imshow("Correction curves",curvesImg);
vector<Mat> ch;
cv::split(Img,ch);
LUT(ch[0],Mat(256,1,CV_8UC1,LUT_BLUE),ch[0]);
LUT(ch[2],Mat(256,1,CV_8UC1,LUT_RED),ch[2]);
LUT(ch[1],Mat(256,1,CV_8UC1,LUT_GREEN),ch[1]);
cv::merge(ch,result);
imshow("Transformed",result);
}
// ---------------------------------
//
// ---------------------------------
//==============================================================================
int main( int argc, char** argv )
{
for (int i=0;i<256;++i)
{
LUT_RED[i]=i;
LUT_GREEN[i]=i;
LUT_BLUE[i]=i;
}
namedWindow("Image");
namedWindow("Correction curves");
namedWindow("Transformed");
Img=imread("D:\\ImagesForTest\\lena.jpg",1);
imshow("Image",Img);
curvesImg=Mat::zeros(256,768,CV_8UC3);
setMouseCallback("Correction curves", mouseHandler, NULL);
waitKey(0);
getchar();
}

Related

Access violation error on stereolabs

I'm writing a program to convert an image sensed with a StereoLabs ZED stereocamera to an OpenCV image, to do some processing, here is the code (including the setup part een if I don't know if the problem can be there):
#include "stdafx.h"
#include "sl/camera.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
using namespace sl;
cv::Mat zed_to_ocv(sl::Mat zed_mat) {
int cv_type = -1;
switch (zed_mat.getDataType()) {
case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
default: break;
}
return cv::Mat(zed_mat.getHeight(), zed_mat.getWidth(), cv_type, zed_mat.getPtr<sl::uchar1>(MEM_CPU));
}
int main(int argc, char **argv) {
InitParameters parameters;
parameters.depth_mode = DEPTH_MODE_PERFORMANCE;
parameters.coordinate_units = UNIT_METER;
parameters.camera_fps = 30;
if (argc > 1) {
parameters.svo_input_filename = argv[1];
}
sl::Camera zed;
ERROR_CODE err = zed.open(parameters);
if (err != SUCCESS) {
zed.close();
cout << "Error while opening ZED camera";
return -1;
}
RuntimeParameters runtime_parameters;
runtime_parameters.sensing_mode = SENSING_MODE_STANDARD;
Resolution image_size = zed.getResolution();
int new_width = image_size.width;
int new_height = image_size.height;
sl::Mat image_zed(new_width, new_height, MAT_TYPE_8U_C4);
cv::Mat image_ocv = zed_to_ocv(image_zed);
cv::Mat image(new_width, new_height, CV_8UC1);
while (true) {
if (zed.grab(runtime_parameters) == SUCCESS) {
zed.retrieveImage(image_zed, VIEW_LEFT, MEM_CPU, new_width, new_height);
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
imshow("camera", image);
waitKey(30);
}
}
zed.close();
return 0;
}
This code works just fine, but if I wanted to use 32F matrices instead (changing the type of both image_zed and image) I get a
Exception in correspondence of 0x00007FF97D175400 (opencv_imgproc340d.dll) in projectCV.exe: 0xC0000005: access violation error reading 0x000002C52DC13040.
error. I tried changing to
getPtr<sl::float1>
inside zed_to_ocv, but the error is still there.
EDIT: Debugging I found out the crash happens at line
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
but I still can't figure out why.
What is the problem here? Thanks.

How to edit a frame's content using ffmpeg and opencv?

I am going to edit the content of one frame from a mp4 file using OpenCV and ffmpeg 3.3. However, I encountered some problems such as the width and the height of video are zero, some functions are deprecated. I have changed the old function to updated function, but still cannot extract a correct frame. Please help.
Can anyone show an example of extracting a frame from a mp4 file using ffmpeg 3.3?
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
// FFmpeg
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/avutil.h>
#include <libavutil/pixdesc.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}
#define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
int main(int argc, char* argv[])
{
// initialize FFmpeg library
av_register_all();
// av_log_set_level(AV_LOG_DEBUG);
int ret;
// open input file context
AVFormatContext* inctx = nullptr;
//ret = avformat_open_input(&inctx, infile, nullptr, nullptr);
ret = avformat_open_input(&inctx, "C:\\car.mp4", nullptr, nullptr);
// retrive input stream information
ret = avformat_find_stream_info(inctx, nullptr);
if (ret < 0) {
std::cerr << "fail to avformat_find_stream_info: ret=" << ret;
return 2;
}
// find primary video stream
AVCodec* vcodec = nullptr;
vcodec = avcodec_find_decoder(AV_CODEC_ID_MPEG4);
if (!vcodec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
const int vstrm_idx = ret;
AVStream* vstrm = inctx->streams[vstrm_idx];
// open video decoder context
AVCodecContext *c = NULL;
c = avcodec_alloc_context3(vcodec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
if (avcodec_open2(c, vcodec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
// print input video stream informataion
// initialize sample scaler
c->pix_fmt = AV_PIX_FMT_YUV420P;
c->width = 1280;
c->height = 720;
if (vcodec->capabilities & CODEC_CAP_TRUNCATED)
c->flags |= CODEC_FLAG_TRUNCATED;
c->flags2 |= CODEC_FLAG2_FAST;
int width = 1280;
int height = 720;
SwsContext* swsctx = sws_getCachedContext(nullptr, width,
height, AV_PIX_FMT_YUV420P, width, height, AV_PIX_FMT_RGB32,
SWS_FAST_BILINEAR, NULL, NULL, NULL);
}
Not sure about writing processed frames, not remember, but seems this worked for me:
extern "C" {
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>
#include "libavcodec/avcodec.h"
#include <libavutil/opt.h>
#include <libavdevice/avdevice.h>
#include <libswscale/swscale.h>
#include <libavutil/mathematics.h>
}
#include "opencv2/opencv.hpp"
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#endif
using namespace std;
using namespace cv;
static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt, const char *tag)
{
AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
char buf1[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_string(buf1, pkt->pts);
char buf2[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_string(buf1, pkt->dts);
char buf3[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_string(buf1, pkt->duration);
char buf4[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_time_string(buf1, pkt->pts, time_base);
char buf5[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_time_string(buf1, pkt->dts, time_base);
char buf6[AV_TS_MAX_STRING_SIZE] = { 0 };
av_ts_make_time_string(buf1, pkt->duration, time_base);
printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
buf1, buf4,
buf2, buf5,
buf3, buf6,
pkt->stream_index);
}
int main(int argc, char **argv)
{
AVOutputFormat *ofmt = NULL;
AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
AVPacket pkt;
AVFrame *pFrame = NULL;
AVFrame *pFrameRGB = NULL;
int frameFinished = 0;
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
const char *in_filename, *out_filename;
int ret, i;
in_filename = "../../TestClips/Audio Video Sync Test.mp4";
out_filename = "out.avi";
// Initialize FFMPEG
av_register_all();
// Get input file format context
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0)
{
fprintf(stderr, "Could not open input file '%s'", in_filename);
goto end;
}
// Extract streams description
if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0)
{
fprintf(stderr, "Failed to retrieve input stream information");
goto end;
}
// Print detailed information about the input or output format,
// such as duration, bitrate, streams, container, programs, metadata, side data, codec and time base.
av_dump_format(ifmt_ctx, 0, in_filename, 0);
// Allocate an AVFormatContext for an output format.
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
if (!ofmt_ctx)
{
fprintf(stderr, "Could not create output context\n");
ret = AVERROR_UNKNOWN;
goto end;
}
// The output container format.
ofmt = ofmt_ctx->oformat;
// Allocating output streams
for (i = 0; i < ifmt_ctx->nb_streams; i++)
{
AVStream *in_stream = ifmt_ctx->streams[i];
AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
if (!out_stream)
{
fprintf(stderr, "Failed allocating output stream\n");
ret = AVERROR_UNKNOWN;
goto end;
}
ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
if (ret < 0)
{
fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
goto end;
}
out_stream->codec->codec_tag = 0;
if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
{
out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
}
// Open output file
if (!(ofmt->flags & AVFMT_NOFILE))
{
ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
if (ret < 0)
{
fprintf(stderr, "Could not open output file '%s'", out_filename);
goto end;
}
}
// Write output file header
ret = avformat_write_header(ofmt_ctx, NULL);
if (ret < 0)
{
fprintf(stderr, "Error occurred when opening output file\n");
goto end;
}
// Search for input video codec info
AVCodec *in_codec = NULL;
AVCodecContext* avctx = NULL;
int video_stream_index = -1;
for (int i = 0; i < ifmt_ctx->nb_streams; i++)
{
if (ifmt_ctx->streams[i]->codec->coder_type == AVMEDIA_TYPE_VIDEO)
{
video_stream_index = i;
avctx = ifmt_ctx->streams[i]->codec;
in_codec = avcodec_find_decoder(avctx->codec_id);
if (!in_codec)
{
fprintf(stderr, "in codec not found\n");
exit(1);
}
break;
}
}
// Search for output video codec info
AVCodec *out_codec = NULL;
AVCodecContext* o_avctx = NULL;
int o_video_stream_index = -1;
for (int i = 0; i < ofmt_ctx->nb_streams; i++)
{
if (ofmt_ctx->streams[i]->codec->coder_type == AVMEDIA_TYPE_VIDEO)
{
o_video_stream_index = i;
out_codec = avcodec_find_encoder(ofmt_ctx->streams[i]->codec->codec_id);
if (!out_codec)
{
fprintf(stderr, "out codec not found\n");
exit(1);
}
o_avctx = avcodec_alloc_context3(out_codec);
o_avctx->height = avctx->height;
o_avctx->width = avctx->width;
o_avctx->sample_aspect_ratio = avctx->sample_aspect_ratio;
o_avctx->gop_size = 2;
o_avctx->max_b_frames = 2;
if (out_codec->pix_fmts)
{
o_avctx->pix_fmt = out_codec->pix_fmts[0];
}
else
{
o_avctx->pix_fmt = avctx->pix_fmt;
}
o_avctx->time_base = avctx->time_base;
if (avcodec_open2(o_avctx, out_codec, NULL) < 0)
{
fprintf(stderr, "cannot open encoder\n");
exit(1);
}
break;
}
}
// Show output format info
av_dump_format(ofmt_ctx, 0, out_filename, 1);
// openCV pixel format
enum AVPixelFormat pFormat = AV_PIX_FMT_RGB24;
// Data size
int numBytes = avpicture_get_size(pFormat, avctx->width, avctx->height);
// allocate buffer
uint8_t *buffer = (uint8_t *)av_malloc(numBytes * sizeof(uint8_t));
// fill frame structure
avpicture_fill((AVPicture *)pFrameRGB, buffer, pFormat, avctx->width, avctx->height);
// frame area
int y_size = avctx->width * avctx->height;
// Open input codec
avcodec_open2(avctx, in_codec, NULL);
// Main loop
while (1)
{
AVStream *in_stream, *out_stream;
ret = av_read_frame(ifmt_ctx, &pkt);
if (ret < 0)
{
break;
}
in_stream = ifmt_ctx->streams[pkt.stream_index];
out_stream = ofmt_ctx->streams[pkt.stream_index];
//log_packet(ifmt_ctx, &pkt, "in");
// copy packet
pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AVRounding(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AVRounding(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
pkt.pos = -1;
//log_packet(ofmt_ctx, &pkt, "out");
if (pkt.stream_index == video_stream_index)
{
avcodec_decode_video2(avctx, pFrame, &frameFinished, &pkt);
if (frameFinished)
{
struct SwsContext *img_convert_ctx;
img_convert_ctx = sws_getCachedContext(NULL,
avctx->width,
avctx->height,
avctx->pix_fmt,
avctx->width,
avctx->height,
AV_PIX_FMT_BGR24,
SWS_BICUBIC,
NULL,
NULL,
NULL);
sws_scale(img_convert_ctx,
((AVPicture*)pFrame)->data,
((AVPicture*)pFrame)->linesize,
0,
avctx->height,
((AVPicture *)pFrameRGB)->data,
((AVPicture *)pFrameRGB)->linesize);
sws_freeContext(img_convert_ctx);
// Do some image processing
cv::Mat img(pFrame->height, pFrame->width, CV_8UC3, pFrameRGB->data[0], false);
cv::GaussianBlur(img, img, Size(5, 5), 3);
cv::imshow("Display", img);
cv::waitKey(5);
// --------------------------------
// Transform back to initial format
// --------------------------------
img_convert_ctx = sws_getCachedContext(NULL,
avctx->width,
avctx->height,
AV_PIX_FMT_BGR24,
avctx->width,
avctx->height,
avctx->pix_fmt,
SWS_BICUBIC,
NULL,
NULL,
NULL);
sws_scale(img_convert_ctx,
((AVPicture*)pFrameRGB)->data,
((AVPicture*)pFrameRGB)->linesize,
0,
avctx->height,
((AVPicture *)pFrame)->data,
((AVPicture *)pFrame)->linesize);
int got_packet = 0;
AVPacket enc_pkt = { 0 };
av_init_packet(&enc_pkt);
avcodec_encode_video2(o_avctx, &enc_pkt, pFrame, &got_packet);
if (o_avctx->coded_frame->pts != AV_NOPTS_VALUE)
{
enc_pkt.pts = av_rescale_q(o_avctx->coded_frame->pts, o_avctx->time_base, ofmt_ctx->streams[video_stream_index]->time_base);
}
if (o_avctx->coded_frame->key_frame)
{
enc_pkt.flags |= AV_PKT_FLAG_KEY;
}
av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
av_packet_unref(&enc_pkt);
sws_freeContext(img_convert_ctx);
}
}
else // write sound frame
{
ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
}
if (ret < 0)
{
fprintf(stderr, "Error muxing packet\n");
break;
}
// Decrease packet ref counter
av_packet_unref(&pkt);
}
av_write_trailer(ofmt_ctx);
end:
avcodec_close(avctx);
avcodec_close(o_avctx);
av_free(pFrame);
av_free(pFrameRGB);
avformat_close_input(&ifmt_ctx);
// close output
if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
{
avio_closep(&ofmt_ctx->pb);
}
avformat_free_context(ofmt_ctx);
if (ret < 0 && ret != AVERROR_EOF)
{
char buf_err[AV_ERROR_MAX_STRING_SIZE] = { 0 };
av_make_error_string(buf_err, AV_ERROR_MAX_STRING_SIZE, ret);
fprintf(stderr, "Error occurred: %s\n", buf_err);
return 1;
}
return 0;
}

openCV:capture images from webcam but only greysreen

Can anyone tell me what's wrong with my code? I can use my webcam by other code, so there is nothing do with the supported problem. In my code below, I must set the camera index into a loop so that i can motivate my camera(the led inductor is on, simply set "CvCapture* camera=cvCaptureFromCAM(0)" can not run! that's wierd!).However, I just can obtain a greysreen,why?
#include "highgui.h"
#include "cv.h"
int main(int grac, char** grav)
{
CvCapture* camera;
int index;
for (index = -1; index <1; index++)
{
camera = cvCaptureFromCAM(index);
if (camera)
{
printf("%d\n", index);
IplImage* f;
cvNamedWindow("camera", CV_WINDOW_AUTOSIZE);
while (1)
{
f = cvQueryFrame(camera);
cvShowImage("camera", f);
char c = cvWaitKey(33);
if (c == 27)break;
}
}
}
cvReleaseCapture(&camera);
cvDestroyAllWindows;
}

Polynomial multiplication using linked list in c

Iam working on a program to perform addition,subtraction,multiplication and differentiation operations on a polynomial using linked list in c.
The other operations are working fine except multiplication one.
here is the code
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
struct link{
int coeff;
int pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
void create(struct link *node)
{
char ch;
do
{
printf("\n\nenter coeff:");
scanf("%d",&node->coeff);
printf("\nenter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
printf("\ncontinue(y/n):");
ch=getch();
}
while(ch=='y' || ch=='Y');
}
void show(struct link *node)
{
while(node->next!=NULL)
{
printf("%dx^%d",node->coeff,node->pow);
node=node->next;
if(node->next!=NULL)
printf(" + ");
}
}
void polyadd(struct link *poly1,struct link *poly2,struct link *poly)
{
while(poly1->next && poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}
void polysub(struct link *poly1,struct link *poly2,struct link *poly)
{
while(poly1->next && poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff-poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}
void polymul(struct link *n1, struct link *n2, struct link *n)
{
struct link * n2beg=n2;
while (n1)
{
struct link * temp=(struct link *)malloc(sizeof(struct link));
temp->next=NULL;
n2=n2beg;
while (n2)
{
temp->coeff = n1->coeff * n2->coeff;
temp->pow = n1->pow + n2->pow;
n2 = n2->next;
temp->next=(struct link *)malloc(sizeof(struct link));
temp=temp->next;
temp->next=NULL;
}
polyadd(temp,n,n);
n1 = n1->next;
free(temp);
}
}
void diff(struct link* p1,struct link* p2)
{
while(p1->next!=NULL)
{
p2->coeff=p1->coeff*p1->pow;
p2->pow=p1->pow-1;
p2->next=NULL;
p2->next=(struct link *)malloc(sizeof(struct link));
p2=p2->next;
p2->next=NULL;
p1=p1->next;
}
}
main()
{
int op;
char ch;
do{
poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
printf("\n\nWhat do you want to do?\n1.Addition\n2.Subtraction
\n3.Multiplication\n4.Differentiation\n0.Exit
\nEnter your choice:");
scanf("%d",&op);
switch(op)
{
case 1:
printf("\n\nenter 1st polynomial:");
create(poly1);
printf("\n\nenter 2nd polynomial:");
create(poly2);
printf("\n1st Polynomial:\t");
show(poly1);
printf("\n2nd Polynomial:\t");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\nAdded polynomial:\t");
show(poly);
break;
case 2:
printf("\n\nenter 1st polynomial:\t");
create(poly1);
printf("\n\nenter 2nd polynomial:\t");
create(poly2);
printf("\n\n1st Polynomial:\t");
show(poly1);
printf("\n\n2nd Polynomial:\t");
show(poly2);
polysub(poly1,poly2,poly);
printf("\n\nSubtracted polynomial:\t");
show(poly);
break;
case 3:
printf("\n\nenter 1st polynomial:");
create(poly1);
printf("\n\nenter 2nd polynomial:");
create(poly2);
printf("\n\n1st Polynomial:\t");
show(poly1);
printf("\n\n2nd Polynomial:\t");
show(poly2);
polymul(poly1,poly2,poly);
printf("\n\nMultiplied polynomial:\t");
show(poly);
break;
case 4:
printf("\n\nenter polynomial:");
create(poly1);
printf("\n\nPolynomial:\t");
show(poly1);
diff(poly1,poly2);
printf("\n\nDifferentiated Polynomial:\t");
show(poly2);
break;
}
/* printf("\n Want to continue? Y/N:");
ch=getch();*/
}
while(op);
}
polyadd(temp,n,n) as used in polymul() has trouble coping with using n as a source polynomial and as the sum destination polynomial.
Either re-work polyadd() to cope with parameters that point to the same polynomial or re-work the call of polyadd() in polymul() to use distinct polynomials. Suggest the first.
I did not go through your full code, as I found an error in your create() function. Note that you have passed poly1 to the function create() as argument.
This not correct as C follows call by value. What happens is only the value of poly1 (which is still un-initialised) is passed and *node stores that value. It's better to pass the address of poly1 as argument and catch that value in the function using pointer to pointer.
#include<stdio.h>
#include <conio.h>
struct node
{
int c,e;
struct node *link;
}*start1=NULL,*start2=NULL,*start3=NULL,*temp1,*temp2,*temp3,*new_node;
int delete_dup(int h)
{
struct node *cr,*prev,*run,*tmp;
cr = start3->link;
prev = start3;
while(cr != NULL){
run = start3;
while(run != cr)
{
if(run->e == cr->e)
{
run->c+=cr->c;
tmp = cr;
cr = cr->link;
prev->link = cr;
remove(tmp);h--;
break;
}
run = run->link;
}
if(run == cr){
cr = cr->link;
prev = prev->link;
}
}
return h;
}
void main()
{
int n,m,i,j,k;
puts("Enter the number of terms in first polynomial");
scanf("%d",&n);
for(i=0;i<n;i++)
{
new_node=(struct node*)malloc(sizeof(struct node));
new_node->link=NULL;
puts("C=");
scanf("%d",&new_node->c);
puts("E=");
scanf("%d",&new_node->e);
new_node->link=start1;
start1=new_node;
}
puts("Enter the number of terms in first polynomial");
scanf("%d",&m);
for(i=0;i<m;i++)
{
new_node=(struct node*)malloc(sizeof(struct node));
new_node->link=NULL;
puts("C=");
scanf("%d",&new_node->c);
puts("E=");
scanf("%d",&new_node->e);
new_node->link=start2;
start2=new_node;
}
temp1=start1;
temp2=start2;
i=0; j=0;
while(i<m)
{
j=0; temp1=start1;
while(j<n)
{
new_node=(struct node*)malloc(sizeof(struct node));
new_node->link=NULL;
new_node->c=temp1->c*temp2->c;
new_node->e=temp1->e+temp2->e;
new_node->link=start3;
start3=new_node;
j++;
temp1=temp1->link;
}
temp2=temp2->link;
i++;
}
i=0;
k=delete_dup(m*n);
temp3=start3;
while(i<k-1)
{
printf("(%dx^%d)+",temp3->c,temp3->e);
temp3=temp3->link;
i++;
}
printf("(%dx^%d)",temp3->c,temp3->e);
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
int coef,pow;
struct node *next;
};
struct node* create()
{
int c;
struct node *new_node=NULL;
struct node *head=NULL,*temp;
do{
new_node=(struct node*)malloc(sizeof(struct node));
printf("\nEnter coef :");
scanf("%d",&new_node->coef);
printf("\nEnter power : ");
scanf("%d",&new_node->pow);
if(head==NULL)
{
head=new_node;
head->next=NULL;
temp=new_node;
}
else
{
temp->next=new_node;
temp=temp->next;
temp->next=NULL;
}
printf("\nDo you want to continue :");
scanf("%d",&c);
}while(c==1);
return head;
}
void print(struct node *p)
{
while(p!=NULL)
{
printf("|%d|%d|->",p->coef,p->pow);
p=p->next;
}
}
struct node* create_new(int p, int q)
{
struct node *nn=(struct node*)malloc(sizeof(struct node));
nn->coef=p;
nn->pow=q;
nn->next=NULL;
return nn;
}
struct node* add(struct node *poly1,struct node *poly2)
{
struct node *tempadd,*temp;
struct node *temp1=poly1;
struct node *temp2=poly2,*head=NULL;
while(temp1!=NULL && temp2!=NULL)
{
if(temp1->pow==temp2->pow)
{
tempadd=create_new(temp1->coef+temp2->coef,temp2->pow);
temp1=temp1->next;
temp2=temp2->next;
}
else if(temp1->pow<temp2->pow)
{
tempadd=create_new(temp2->coef,temp2->pow);
temp2=temp2->next;
}
else
{
tempadd=create_new(temp1->coef,temp1->pow);
temp1=temp1->next;
}
if(head==NULL)
{
head=tempadd;
temp=head;
}
else
{
temp->next=tempadd;
temp=temp->next;
}
}
if(temp1!=NULL)
{
while(temp1!=NULL)
{
tempadd=create_new(temp1->coef,temp1->pow);
temp1=temp1->next;
temp->next=tempadd;
temp=temp->next;
}
}
else if(temp2!=NULL)
{
while(temp2!=NULL)
{
tempadd=create_new(temp2->coef,temp2->pow);
temp2=temp2->next;
temp->next=tempadd;
temp=temp->next;
}
}
return head;
}
void main()
{
struct node *head1,*head2,*head3;
head1=create();
print(head1);
head2=create();
print(head1);
printf("\n");
print(head2);
printf("\n");
head3=add(head1,head2);
printf("\n\nResult : ");
print(head3);
getch();
}
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node {
struct node *previous;
int coef;
int pow;
struct node *next;
}poly;
poly *locate(int,poly *);
void display(poly *);
poly *mult(poly *,poly *,poly *);
void display2(poly *);
void main()
{
char ch;
poly *s1,*s2,*s3,*head1,*head2,*head3,*s4;;
s1=(poly *)malloc(sizeof(poly));
s1->previous=NULL;
head1=s1;
s2=(poly *)malloc(sizeof(poly));
s2->previous=NULL;
head2=s2;
head3=s3;
printf("Enter first polynomial :\n");
do{ //Input for polynomial-1
printf("Enter co-efficient : ");
scanf("%d",&s1->coef);
printf("Enter exponent : ");
scanf("%d",&s1->pow);
printf("Do you want to enter more terms(Y/N) : ");
scanf(" %c",&ch);
if(ch=='Y'){
s1->next=(poly*)malloc(sizeof(poly));
s1->next->previous=s1;
s1=s1->next;
}
else {
s1->next=NULL;
break;
}
}while(1);
printf("Enter second polynomial : \n");
do{ //input for polynomial-2
printf("Enter co-efficient : ");
scanf("%d",&s2->coef);
printf("Enter exponent : ");
scanf("%d",&s2->pow);
printf("Do you want to enter more terms(Y/N) : ");
scanf(" %c",&ch);
if(ch=='Y'){
s2->next=(poly*)malloc(sizeof(poly));
s2->next->previous=s2;
s2=s2->next;
}
else {
s2->next=NULL;
break;
}
}while(1);
printf("Entered polynomials are : \n");
display(s1);
printf("\n");
display(s2);
s3=NULL;
s4=mult(s1,s2,s3);
printf("Resultant Polynomial after multiplication :\n");
display(s4);
}
void display(poly *a)
{
while(a!=NULL)
{
printf("%dx^%d",a->coef,a->pow);
if(a->previous!=NULL)
printf(" + ");
a=a->previous;
}
}
poly *mult(poly *s1,poly *s2,poly *s3)
{
while(s1->previous!=NULL)
s1=s1->previous;
while(s2->previous!=NULL)
s2=s2->previous;
while(s1)
{
while(s2->previous!=NULL)
s2=s2->previous;
while(1)
{
if(s2->next!=NULL)
{
poly *s4;
if(s3==NULL)
{
s3=(poly *)malloc(sizeof(poly));
s3->pow=s1->pow+s2->pow;
s3->coef=s1->coef*s2->coef;
s3->previous==NULL;
s3->next==NULL;
}
else
{
s4=locate(s1->pow+s2->pow,s3);
if(s4==NULL)
{
s3->next=(poly *)malloc(sizeof(poly));
s3->next->previous=s3;
s3=s3->next;
s3->pow=s1->pow+s2->pow;
s3->coef=s1->coef*s2->coef;
s3->next==NULL;
}
else
{
s4->coef=(s4->coef)+(s1->coef*s2->coef);
}
}
s2=s2->next;
}
else
{
poly *s4;
if(s3==NULL)
{
s3=(poly *)malloc(sizeof(poly));
s3->pow=s1->pow+s2->pow;
s3->coef=s1->coef*s2->coef;
s3->previous==NULL;
s3->next==NULL;
}
else{
s4=locate(s1->pow+s2->pow,s3);
if(s4==NULL)
{
s3->next=(poly *)malloc(sizeof(poly));
s3->next->previous=s3;
s3=s3->next;
s3->pow=s1->pow+s2->pow;
s3->coef=s1->coef*s2->coef;
s3->next==NULL;
}
else
{
s4->coef=s4->coef+s1->coef*s2->coef;
}
}
break;
};
}s1=s1->next;
}return s3;
}
poly *locate(int exp,poly *s3)
{
if(s3==NULL)
{
return NULL;
}
else if(s3->pow==exp)
{
return s3;
}
else{
return locate(exp,s3->previous);
}
}
I considered the first term of first polynomial and multiplied with all the terms of second polynomial thereby creating a primary linked list of multiplied polynomial. As next piece of code I considered next term of first polynomial and then multiplied and searched in the multiplied polynomial for the same index and added the result to it, If it is not present I created a new node in the multiplied polynomial.
Happy Coding

CodeBook background subtraction with moving objects

I am trying to use CodeBook method for OpenCV to subtract the background. So far so good, but I am not sure if I can update the codebook for moving objects after some time span, say 5 minutes, I need to update the codebook after which I get lots of moving objects. How do I make sure that after 5 minutes I have a background that needs to be updated?
Thanks for the tips!
kim's algorithm supposedly has a cache layer, i did not dig deep enough into opencv implementation to know how to have a workable version that works with exposure problem.
notes
opencv book(which i havent read) should have the info you need if it's there at all
this is only 1 channel and not in yuv although it can be extended
needs more work on speed/testing (you can of course turn on optimization in compiler)
background subtraction is a buzzy word. try "change detection"
bgfg_cb.h
#ifndef __bgfg_cb_h__
#define __bgfg_cb_h__
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.148.9778&rep=rep1&type=pdf
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <time.h>
using namespace cv;
using namespace std;
struct codeword {
float min;
float max;
float f;
float l;
int first;
int last;
bool isStale;
};
extern int alpha ;
extern float beta ;
extern int Tdel ,Tadd , Th;
void initializeCodebook(int w,int h);
void update_cb(Mat& frame);
void fg_cb(Mat& frame,Mat& fg);
#endif
bgfg_cb.cpp
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <time.h>
#include "bgfg_cb.h"
using namespace cv;
using namespace std;
vector<codeword> **cbMain;
vector<codeword> **cbCache;
int t=0;
int alpha = 10;//knob
float beta =1;
int Tdel = 200,Tadd = 150, Th= 200;//knobs
void initializeCodebook(int w,int h)
{
cbMain = new vector<codeword>*[w];
for(int i = 0; i < w; ++i)
cbMain[i] = new vector<codeword>[h];
cbCache = new vector<codeword>*[w];
for(int i = 0; i < w; ++i)
cbCache[i] = new vector<codeword>[h];
}
void update_cb(Mat& frame)
{
if(t>10) return;
for(int i=0;i<frame.rows;i++)
{
for(int j=0;j<frame.cols;j++)
{
int pix = frame.at<uchar>(i,j);
vector<codeword>& cm =cbMain[i][j];
bool found = false;
for(int k=0;k<cm.size();k++)
{
if(cm[k].min<=pix && pix<=cm[k].max && !found)
{
found=true;
cm[k].min = ((pix-alpha)+(cm[k].f*cm[k].min))/(cm[k].f+1);
cm[k].max = ((pix+alpha)+(cm[k].f*cm[k].max))/(cm[k].f+1);
cm[k].l=0;
cm[k].last=t;
cm[k].f++;
}else
{
cm[k].l++;
}
}
if(!found)
{
codeword n={};
n.min=max(0,pix-alpha);
n.max=min(255,pix+alpha);
n.f=1;
n.l=0;
n.first=t;
n.last=t;
cm.push_back(n);
}
}
}
t++;
}
void fg_cb(Mat& frame,Mat& fg)
{
fg=Mat::zeros(frame.size(),CV_8UC1);
if(cbMain==0) initializeCodebook(frame.rows,frame.cols);
if(t<10)
{
update_cb(frame);
return;
}
for(int i=0;i<frame.rows;i++)
{
for(int j=0;j<frame.cols;j++)
{
int pix = frame.at<uchar>(i,j);
vector<codeword>& cm = cbMain[i][j];
bool found = false;
for(int k=0;k<cm.size();k++)
{
if(cm[k].min<=pix && pix<=cm[k].max && !found)
{
cm[k].min = ((1-beta)*(pix-alpha)) + (beta*cm[k].min);
cm[k].max = ((1-beta)*(pix+alpha)) + (beta*cm[k].max);
cm[k].l=0;
cm[k].first=t;
cm[k].f++;
found=true;
}else
{
cm[k].l++;
}
}
cm.erase( remove_if(cm.begin(), cm.end(), [](codeword& c) { return c.l>=Tdel;} ), cm.end() );
fg.at<uchar>(i,j) = found?0:255;
if(found) continue;
found = false;
vector<codeword>& cc = cbCache[i][j];
for(int k=0;k<cc.size();k++)
{
if(cc[k].min<=pix && pix<=cc[k].max && !found)
{
cc[k].min = ((1-beta)*(pix-alpha)) + (beta*cc[k].min);
cc[k].max = ((1-beta)*(pix+alpha)) + (beta*cc[k].max);
cc[k].l=0;
cc[k].first=t;
cc[k].f++;
found=true;
}else
{
cc[k].l++;
}
}
if(!found)
{
codeword n={};
n.min=max(0,pix-alpha);
n.max=min(255,pix+alpha);
n.f=1;
n.l=0;
n.first=t;
n.last=t;
cc.push_back(n);
}
cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.l>=Th;} ), cc.end() );
for(vector<codeword>::iterator it=cc.begin();it!=cc.end();it++)
{
if(it->f>Tadd)
{
cm.push_back(*it);
}
}
cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.f>Tadd;} ), cc.end() );
}
}
}
main.cpp
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "bgfg_cb.h"
#include <iostream>
using namespace cv;
using namespace std;
void proc()
{
Mat frame,fg,gray;
VideoCapture cap("C:/Downloads/S2_L1.tar/S2_L1/Crowd_PETS09/S2/L1/Time_12-34/View_001/frame_%04d.jpg");
cap >> frame;
initializeCodebook(frame.rows,frame.cols);
for(;;)
{
cap>>frame;
cvtColor(frame,gray,CV_BGR2GRAY);
fg_cb(gray,fg);
Mat cc;
imshow("fg",fg);
waitKey(1);
}
}
int main(int argc, char ** argv)
{
proc();
cin.ignore(1);
return 0;
}

Resources