Created
October 5, 2015 07:10
-
-
Save ArdWar/642f772ef046679a31d8 to your computer and use it in GitHub Desktop.
[OpenCV] Line counter using edge detection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "opencv/cv.h" | |
#include "opencv/highgui.h" | |
#include <stdio.h> | |
void dy(IplImage* buf1, IplImage* out) { | |
for (int x=0;x<buf1->width;x++) { | |
for (int y=0;y<buf1->height;y++) { | |
out->imageData[out->widthStep*y+x]=abs((uchar)buf1->imageData[buf1->widthStep*(y+1)+x]-(uchar)buf1->imageData[buf1->widthStep*y+x]); | |
} | |
} | |
} | |
void extract(IplImage* buf, IplImage* out) { | |
for (int x=0;x<buf->width;x++) { | |
for (int y=0;y<16;y++) { out->imageData[out->widthStep*y+x]=buf->imageData[buf->widthStep*(buf->height-120+y)+x]; } | |
} | |
} | |
int count(IplImage* strip) { | |
int cnt=0, out; | |
for (int x=0;x<strip->width;x++) { | |
for (int y=0;y<strip->height;y++) { cnt+=((uchar)strip->imageData[strip->widthStep*y+x])/255; } | |
} | |
if (cnt<5000) { | |
if (cnt<4500) { out=0; } | |
else { out=1; } | |
} | |
else { out=2; } | |
return(out); | |
} | |
void comb(IplImage*a, IplImage*b) { | |
for (int x=0;x<b->width;x++) { | |
for (int y=0;y<16;y++) { a->imageData[a->widthStep*(a->height-120+y)+x]=b->imageData[b->widthStep*y+x]; } | |
} | |
} | |
void main() { | |
IplImage* img; | |
CvCapture* cap=cvCaptureFromCAM(0); | |
cvNamedWindow("Line Counter", 1); | |
CvFont* font1=new CvFont; | |
CvFont* font2=new CvFont; | |
cvInitFont(font1, CV_FONT_HERSHEY_SIMPLEX, 0.5f, 1.0f, 0, 3, 8); | |
cvInitFont(font2, CV_FONT_HERSHEY_SIMPLEX, 0.5f, 1.0f, 0, 2, 8); | |
int val=0, axx=0, bxx=0; | |
char text[8]; | |
for (;;) { | |
img = cvQueryFrame(cap); | |
if (!img) break; | |
IplImage* gray1=cvCreateImage(cvSize(img->width, img->height), 8, 1); | |
IplImage* edge1=cvCreateImage(cvSize(img->width, 16), 8, 1); | |
cvCvtColor(img, gray1, 7); | |
extract(gray1, edge1); | |
dy(edge1, edge1); | |
cvThreshold(edge1, edge1, 10, 255, CV_THRESH_BINARY_INV); | |
val=count(edge1); | |
if (val==0&&axx==0) { axx=1; } | |
if (val==2&&axx==1) { axx=0; bxx++; } | |
sprintf(text, "%i", bxx); | |
comb(gray1, edge1); | |
cvPutText(gray1, text, cvPoint(10, 160), font1, cvScalarAll(255)); | |
cvPutText(gray1, text, cvPoint(10, 160), font2, cvScalarAll(0)); | |
cvShowImage("Line Counter", gray1); | |
if (cvWaitKey(5) > 0) break; | |
cvReleaseImage(&gray1); | |
cvReleaseImage(&edge1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment