So it basically has 3 lines, and i want for long trades that closed bar price has crossed middle line up, but not upper line. i Cannot get it work in my if statement.
At the moment i do get middle line cross up, but it also shows buy signal if candle crosses upper line which is not good. Please help...
my EA code:
// the input variables of the EA
input ENUM_TIMEFRAMES TimeFrame = PERIOD_CURRENT;
input int AMAPeriod = 10;
input ENUM_APPLIED_PRICE AMAPrice = PRICE_CLOSE;
input int Nfast = 2;
input int Nslow = 30;
input double GCoeff = 2;
input int PriceFilter = 5;
input maTypes PriceFilterMode = ma_smoo;
input bool Interpolate = true;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
double band_middle = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter, PriceFilterMode,Interpolate, 0,0 );
double band_1 = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode,Interpolate, 1,0 );
double band_2 = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode,Interpolate, 2,0 );
double band_3 = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode, Interpolate, 3,0 );
double band_up = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode, Interpolate, 4,0 );
double band_down = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode, Interpolate, 5,0 );
//strategy
double band_middle_curr = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter, PriceFilterMode,Interpolate, 0,0 );
double band_middle_prev = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter, PriceFilterMode,Interpolate, 0,1 );
double band_up_prev = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode, Interpolate, 4,1 );
double band_up_curr = iCustom(_Symbol,_Period,"kaufman_ama_averages_filtered_ATR bands",TimeFrame, AMAPeriod, AMAPrice,Nfast, Nslow, GCoeff, PriceFilter,PriceFilterMode, Interpolate, 4,0 );
Comment(band_up_prev);
if(Close[0] > band_middle_curr && Close[0] < band_up_curr)
{
Print("open a buy order");
}
}
//+------------------------------------------------------------------+
Use Close[1]. Close[0] is the current bar which is not finished yet.
Related
i have a small expert with mql4 for forex robot
but i have get some problem in getting code when running this code to backtest in metatrader 4
my code details is :
i have 2 ema and when cross up get buy and when cross down get sell
but its problem to get position after crosing 2 ema in backtest.
My stoplose is fix to 10 pip but tp is 0 and we have open trade until next cross from 2 ema and then close pervios position and get new position.
i add test sterategy and show my problem in getting position
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input double StopLoss = 100;
input double TakeProfit = 0;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
BuyCondition = False;
GetBuy();
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
SellCondition = False;
GetSell();
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
int GetBuy(){
int getposition = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
return True;
}
int GetSell(){
int getposition = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),0,"Sell",MagicNumber,0,Red);
return True;
}
enter image description here
I edited your code. The main problem in your code is takeprofit!
In GetBuy() and GetSell() Functions you wrote:
Ask+(TakeProfit*Point)
It returns Ask! because your TakeProfit has been set to zero. If you don't want to set Takeprofit You should write:
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
This is the new code:
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input int StopLoss = 100;
input int TakeProfit = 1000;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_SELL ? Ask : Bid, Slippage, clrWhite );
}
if(GetBuy()) BuyCondition = False;
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_BUY ? Bid : Ask, Slippage, clrWhite );
}
if(GetSell()) SellCondition = False;
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
bool GetBuy(){
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),Ask+ (TakeProfit*Point),"Buy",MagicNumber,0,Blue);
if(ticket > 0) return true;
return false;
}
bool GetSell(){
int ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),Bid- (TakeProfit*Point),"Sell",MagicNumber,0,Red);
if(ticket > 0) return true;
return false;
}
This is my code trying to generate the ADC Cloud indicator.
At first, it can work if I just generate the cloud.
Currently, I am trying to make the histogram green when it is above zero, otherwise red. Then, I separate the Could array into two buffers, GreenBuffer and RedBuffer. At this step, I stuck in an unknown error.
I can make sure the problem is coming from the ERROR PART, marked by Sharp Sign in Code.
Thank you first!
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period=14;
double Cloud[];
double GreenBuffer[];
double RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
//SetIndexBuffer(0, GreenBuffer);
SetIndexBuffer(0, Cloud);
SetIndexLabel(0, "Cloud");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
//SetIndexBuffer(1, Cloud);
//SetIndexStyle(1, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int Limit_calc = 0;
int BarCnt = IndicatorCounted();
Limit_calc = Bars - BarCnt;
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
Cloud[i] = output;
// #########################################
// ###### Error Part #######################
//if (output > 0)
// {
// GreenBuffer[i] = output;
// RedBuffer[i] = 0.00;
// }
//else
// {
// GreenBuffer[i] = 0.00;
// RedBuffer[i] = output;
// }
// ##########################################
}
//Comment(Cloud[1]);
//--- return value of prev_calculated for next call
return(rates_total);
}
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0, GreenBuffer);
SetIndexLabel(0, "Green");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
SetIndexBuffer(0, RedBuffer);
SetIndexLabel(0, "Red");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
int OnCalculate( *** )
{
...
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
if (output > 0)
{
GreenBuffer[i] = output;
RedBuffer[i] = 0.00;
}
else
{
GreenBuffer[i] = 0.00;
RedBuffer[i] = output;
}
}
...
}
REPAIRED & [PASS]-on-TESTED CODE :
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period = 14;
double GreenBuffer[],
RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer( 0, GreenBuffer );
SetIndexLabel( 0, "Green" );
SetIndexStyle( 0, DRAW_HISTOGRAM, 0, 2, clrGreen );
SetIndexBuffer( 1, RedBuffer );
SetIndexLabel( 1, "Red" );
SetIndexStyle( 1, DRAW_HISTOGRAM, 0, 2, clrRed );
//---
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate( const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
)
{
//---
int BarCnt = IndicatorCounted();
int Limit_calc = Bars - BarCnt;
for ( int i = Limit_calc - 1; i >= 0 ; i-- )
{
double output = iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i )
- iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i );
if ( output > 0 ) { GreenBuffer[i] = output; RedBuffer[i] = 0.00; }
else { GreenBuffer[i] = 0.00; RedBuffer[i] = output; }
}
//---
return( rates_total );
}
For a learning purpose, I am trying to code a simple MA indicator that changes color when price crosses. Though there are no errors, it draws nothing. Could you review the attached code to show me my mistake?
#property indicator_chart_window
#property indicator_buffers 2
extern int maperiod = 20;
extern int maprice = PRICE_CLOSE;
extern int mamethod = MODE_SMA;
extern color colorup = Green;
extern color colordn = Red;
double mamain[];
double bufferup[];
double bufferdn[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init(){
//--- indicator buffers mapping
SetIndexBuffer( 0, bufferup );
SetIndexStyle( 0, DRAW_LINE, 0, 2, colorup );
SetIndexBuffer( 1, bufferdn );
SetIndexStyle( 1, DRAW_LINE, 0, 2, colordn );
//---
return( 0 );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start(){
//---
int counted_bars = IndicatorCounted();
if ( counted_bars < 0 ) return( -1 );
if ( counted_bars > 0 ) counted_bars--;
int limit = Bars - counted_bars;
for ( int i = limit; i >= 0 ; i-- )
{ mamain[i] = iMA( NULL, 0, maperiod, 0, 0, 0, i );
if ( mamain[i] >= iClose( NULL, 0, i ) ) bufferup[i] = mamain[i];
if ( mamain[i] <= iClose( NULL, 0, i ) ) bufferdn[i] = mamain[i];
}
//--- return value of prev_calculated for next call
return( 0 );
}
//+------------------------------------------------------------------+
"Old"-MQL4 may work for some time, but still, get used to new features:
extern ENUM_APPLIED_PRICE MAprice = PRICE_CLOSE; // AVOIDS incompatible values
extern ENUM_MA_METHOD MAmethod = MODE_SMA; // AVOIDS incompatible values
#define MAshift 0 // ADDS code == intent match-robustness
extern int MAperiod = 20;
extern color colorUP = clrGreen;
extern color colorDN = clrRed;
double bufferUP[];
double bufferDN[];
int init(){
ArrayInitialize bufferUP, EMPTY_VALUE );
SetIndexBuffer( 0, bufferUP );
SetIndexStyle( 0, DRAW_LINE, EMPTY, 2, colorUP );
SetIndexLabel( 0, "MA_ABOVE_Close" );
ArrayInitialize bufferDN, EMPTY_VALUE );
SetIndexBuffer( 1, bufferDN );
SetIndexStyle( 1, DRAW_LINE, EMPTY, 2, colorDN );
SetIndexLabel( 1, "MA_UNDER_Close" );
return( 0 );
}
int start(){
int counted_bars = IndicatorCounted();
if ( counted_bars < 0 ) return( -1 );
if ( counted_bars > 0 ) counted_bars--;
for ( int i = Bars - counted_bars; i >= 0 ; i-- ){
double C = iClose( _Symbol, PERIOD_CURRENT, i ),
A = iMA( _Symbol, PERIOD_CURRENT,
MAperiod,
MAshift,
MAmethod,
MAprice,
i
);
if ( A >= C ) bufferUP[i] = A;
if ( A <= C ) bufferDN[i] = A;
}
return( 0 );
}
New-MQL4.56789 uses another call-signature if #property strict:
int OnCalculate( const int rates_total,
const int prev_calculated,
const datetime &time_______ARR[],
const double &open_______ARR[],
const double &high_______ARR[],
const double &low________ARR[],
const double &close______ARR[],
const long &tick_volumeARR[],
const long &volume_____ARR[],
const int &spread_____ARR[]
){
//--- the main loop of calculations
for( int i = prev_calculated - 1;
( i < rates_total
&& !IsStopped() ); // AVOID SHARED (!) solo-THREAD BLOCKING
i++
){
// -----------------------------------------------------------------
double A = iMA( _Symbol, PERIOD_CURRENT,
MAperiod,
MAshift,
MAmethod,
MAprice,
i
);
if ( A >= close______ARR[i] ) bufferUP[i] = A;
if ( A <= close______ARR[i] ) bufferDN[i] = A;
// -----------------------------------------------------------------
}
return( rates_total );
}
your buffer mamain[] is not initialized.
int init(){
IndicatorBuffers(3);
SetIndexBuffer(2,mamain);
}
rates_total and prev_calculated seems preferred but of course you can use IndicatorCounted() but keep in mind the corner situation with the first bar: when you first attach the indicator to the chart, your counted_bars = 0 and limit = Bars, but mamain[] and other indicator buffers have Bars elements only, from 0 to Bars-1. so better to use
int limit = Bars - counted_bars - 1;
About resolving issues - in addition to asking here you can always try to attach your indicator to a chart and see it there's no error (terminal window - Experts folder), that will make delevopment faster
I want to find subpixel and I resarched this topic However I think that subpixels must be such as 152.6 , 49.3 ...
I find this document in opencv http://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=cornersubpix#cornersubpix
And I try this code
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
Mat src, src_gray;
int maxCorners = 10;
int maxTrackbar = 50;
RNG rng(11111);
char* source_window = "Image";
void goodFeaturesToTrack_Demo( int, void* );
int main( int argc, char** argv )
{
src = imread( "a.png", 1 );
cvtColor( src, src_gray, CV_BGR2GRAY );
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
createTrackbar( "Max corners:", source_window, &maxCorners, maxTrackbar, goodFeaturesToTrack_Demo);
imshow( source_window, src );
goodFeaturesToTrack_Demo( 0, 0 );
waitKey(0);
return(0);
}
void goodFeaturesToTrack_Demo( int, void* )
{
if( maxCorners < 1 )
{ maxCorners = 1; }
vector<Point2f> corners;
double qualityLevel = 0.01;
double minDistance = 10;
int blockSize = 3;
bool useHarrisDetector = false;
double k = 0.04;
Mat copy;
copy = src.clone();
goodFeaturesToTrack( src_gray,corners,maxCorners,qualityLevel,minDistance,Mat(),blockSize,useHarrisDetector,k );
cout<<"** Number of corners detected: "<<corners.size()<<endl;
int r = 4;
for( int i = 0; i < corners.size(); i++ )
{ circle( copy, corners[i], r, Scalar(rng.uniform(0,255), rng.uniform(0,255),rng.uniform(0,255)), -1, 8, 0 ); }
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, copy );
Size winSize = Size( 10, 10 );
Size zeroZone = Size( -1, -1 );
TermCriteria criteria = TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001 );
cornerSubPix( src_gray, corners, winSize, zeroZone, criteria );
for( int i = 0; i < corners.size(); i++ )
{ cout<<" -- Refined Corner ["<<i<<"] ("<<corners[i].x<<","<<corners[i].y<<")"<<endl; }
}
But I have this result:
this code ofind only corner's subpixel I want to find edge's subpixel
I'm trying to use the optical flow, but optical flow lines are not drawn and instead only points, what's the problem ?
Here is the source code of the project. Looked through the debugger. GDB shows that always p0.x = p1.x and p0.y = p1.y. but why ? Sorry for my bad English.
#include "opencv/cv.h"
#include "opencv2/core/core.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
std::vector<cv::Point2f> corners;
std::vector<cv::Point2f> corners_b;
double qualityLevel = 0.01;
double minDistance = 10;
int blockSize = 3;
bool useHarrisDetector = false;
double k = 0.04;
int maxCorners = 200;
int maxTrackbar = 100;
void MotionDetection(cv::Mat frame1, cv::Mat frame2)
{
cv::Mat prev, next;
cvtColor(frame1, prev, CV_BGR2GRAY);
cvtColor(frame2, next, CV_BGR2GRAY);
goodFeaturesToTrack( prev,
corners,
maxCorners,
qualityLevel,
minDistance,
cv::Mat(),
blockSize,
useHarrisDetector,
k );
cornerSubPix(prev,
corners,
cvSize( 10, 10 ) ,
cvSize( -1, -1 ),
cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03 ) );
std::vector<uchar> features_found;
features_found.reserve(maxCorners);
std::vector<float> feature_errors;
feature_errors.reserve(maxCorners);
calcOpticalFlowPyrLK(prev, next, corners, corners_b, features_found,
feature_errors, cvSize( 10, 10 ), 5, cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.3 ), 0);
IplImage g = next;
for( int i = 0; i < maxCorners; ++i )
{
CvPoint p0 = cvPoint( cvRound( corners[i].x ), cvRound( corners[i].y ) );
CvPoint p1 = cvPoint( cvRound( corners_b[i].x ), cvRound( corners_b[i].y ) );
cvLine( &g, p0, p1, CV_RGB(255,0,0), 3, CV_AA );
}
cv::Mat rs(&g);
imshow( "result window", rs );
int key = cv::waitKey(5);
}
int main(int argc, char* argv[])
{
cv::VideoCapture cap(0);
if(!cap.isOpened())
{
std::cout<<"[!] Error: cant open camera!"<<std::endl;
return -1;
}
cv::Mat edges;
cv::namedWindow("result window", 1);
cv::Mat frame, frame2;
cap >> frame;
while(1)
{
cap >> frame2;
MotionDetection(frame, frame2);
}
return 0;
}
in you Main function frame is clone frame2.
I think, that
cap >> frame2;
frame2.copyTo( frame );
instead of
cap >> frame;
thats all