Search code examples
opencvimage-processingobject-detectionandroid

how to draw a rectangle by specifying its 4 corners


I am using OpenCV4Android version 2.4.11. I am reading frames from the camera and I detect any rectangular shapes in the frame. Then I try to draw a semi-transparent rectangle around a detected object.

what i want to do is, to draw a semi-transparent rectangale given the four corners of the detected object. But, in openCV you can draw a rectangle by spcifying only two points of it "the topLeft and BottomRight".

please let me know how to draw a rectangle by spcifying the the four corners of it NOT ONLY by spcifying the topLeft and BottomRight corners.

the below posted image is to show you my attempts and to show you that what i want is to draw a rectangle around the four detected corners "red, green, blue, white"

image:

enter image description here


Solution

  • OpenCV doesn't provide a rectangle drawing function, but you can generate the top-left and bottom-right points using the 4 points that you've computed:

    Suppose your 4 points are - (tlx,tly),(trx,try),(blx,bly) and (brx,bry) where tl is top-left and br is bottom right.

    Then you can calculate:

    x1=min(tlx,trx,brx,blx);//top-left pt. is the leftmost of the 4 points
    x2=max(tlx,trx,brx,blx);//bottom-right pt. is the rightmost of the 4 points
    y1=min(tly,try,bry,bly);//top-left pt. is the uppermost of the 4 points
    y2=max(tly,try,bry,bly);//bottom-right pt. is the lowermost of the 4 points
    

    This is assuming that the point (0,0) occurs at the top left. Now you can use:

    rectangle(src, Point(x1,y1), Point(x2,y2),Color,Thickness,other_params);