1

We are using Python OpenCV to detect shapes. I am using code here to detect shapes. https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/

How do I find the width height of the Rectangle below? I could find the greatest subtraction differential between x-values, and greatest-differential of y-values, by looking at all combinations of vertices below. Curious if Python OpenCV library has a more efficient way to conduct this. This algorithm could be more cumbersome, if dealing with Pentagons or Hexagons, or shapes with many vertices contours.

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

for contourItem in cnts:

    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)

    if len(approx) == 3:
        shape = "triangle"

    elif len(approx) == 4:
        (x, y, w, h) = cv2.boundingRect(approx)
        ar = w / float(h)
        shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"

    elif len(approx) == 5:
        shape = "pentagon"

Results of Vertices:

1 = 
 xLocation = 341
 yLocation = 372
2 = 
 xLocation = 277
 yLocation = 410
3 = 
 xLocation = 348
 yLocation = 529
4 = {
 xLocation = 412
 yLocation = 493

Shape Values

Resources: How to detect simple geometric shapes using OpenCV

1 Answers1

0

Use x,y,w,h = cv.boundingRect() as comment above stated or one can also use cv2.minAreaRect().

7.a. Straight Bounding Rectangle It is a straight rectangle, it doesn’t consider the rotation of the object. So area of the bounding rectangle won’t be minimum. It is found by the function cv2.boundingRect().

Let (x,y) be the top-left coordinate of the rectangle and (w,h) be its width and height.

x,y,w,h = cv2.boundingRect(cnt) 
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

7.b. Rotated Rectangle Here, bounding rectangle is drawn with minimum area, so it considers the rotation also. The function used is cv2.minAreaRect(). It returns a Box2D structure which contains following detals - ( top-left corner(x,y), (width, height), angle of rotation ). But to draw this rectangle, we need 4 corners of the rectangle. It is obtained by the function cv2.boxPoints()

rect = cv2.minAreaRect(cnt) 
box = cv2.boxPoints(rect) 
box = np.int0(box)
im = cv2.drawContours(im,[box],0,(0,0,255),2)

Rectangle Image Picture

Thanks also to DragonsCanDance user

From Resource: Python resource