Calculating FPS in OpenCV for Live Capture

cvGetCaptureProperty(CV_CAP_PROP_FPS); simply won’t work for live capture from camera. So following is my workaround, enhanced version of this source:

#include "cv.h"
#include "highgui.h"

#include <stdio.h>
#include <time.h> // to calculate time needed
#include <limits.h> // to get INT_MAX, to protect against overflow

int main(int argc, char** argv){
	CvCapture* capture = cvCaptureFromCAM( 0 );
	if (!capture){
		fprintf(stderr, "ERROR: Capture is null\nPress any key to exit\n");
		return -1;
	// fps counter begin
	time_t start, end;
	int counter = 0;
	double sec;
	double fps;
	// fps counter end
	cvNamedWindow("Original", CV_WINDOW_AUTOSIZE);
		// fps counter begin
		if (counter == 0){
		// fps counter end
		IplImage* origImage = cvQueryFrame(capture);
		cvShowImage("Original", origImage);

		// do your stuff here

		// fps counter begin
		sec = difftime(end, start);
		fps = counter/sec;
		if (counter > 30)
			printf("%.2f fps\n", fps);
		// overflow protection
		if (counter == (INT_MAX - 1000))
			counter = 0;
		// fps counter end

		// will exit when ESC button is pressed
		if ( (cvWaitKey(10) & 255) == 27 ) break;
	return 0;
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: