Skip to content

Instantly share code, notes, and snippets.

@guiyanzhong
Forked from MareArts/overlapPercent.cpp
Created August 29, 2020 07:42
Show Gist options
  • Save guiyanzhong/cf37525bc331dc3639207ae2c81e4878 to your computer and use it in GitHub Desktop.
Save guiyanzhong/cf37525bc331dc3639207ae2c81e4878 to your computer and use it in GitHub Desktop.
openCV Tip, Calculate overlap percent between two rectangle.
http://study.marearts.com/2017/09/opencv-tip-calculate-overlap-percent.html
Mat canvas(100, 100, CV_8UC3);
canvas.setTo(0);
Rect rectA(10, 5, 50, 60);
Rect rectB(40,40,30, 40);
Rect andRect_overlap = (rectA & rectB);
Rect orRect_whole = (rectA | rectB);
cout << "rect A info. : " << rectA << endl;
cout << "rect B info. : " << rectB << endl << endl;
cout << "A and B region info. : " << andRect_overlap << endl;
cout << "A or B region info. : " << orRect_whole << endl << endl;
//if overlapped
if (orRect_whole.width != 0 && orRect_whole.height != 0)
{
double overlap_percentOfA = float(andRect_overlap.area()) / rectA.area() * 100;
double overlap_percentOfB = float(andRect_overlap.area()) / rectB.area() * 100;
cout << "overlap percent in A " << overlap_percentOfA << "%" << endl;
cout << "overlap percent in B " << overlap_percentOfB << "%" << endl;
}
rectangle(canvas, rectA, CV_RGB(255, 0, 0));
rectangle(canvas, rectB, CV_RGB(0, 0, 255));
rectangle(canvas, andRect_overlap, CV_RGB(0, 255, 0),1);
//rectangle(canvas, orRect_whole, CV_RGB(0, 255, 255));
imshow("canvas", canvas);
waitKey(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment