[opencv] Contour attributes (aspect ratio, range, solidity, equivalent diameter, object pointing angle, mask and pixel points, average color, extreme points)

Hits: 0

4_9_3_Contour attribute – OpenCV Chinese official documentation

Extract some commonly used object properties such as firmness, equivalent diameter, mask image, average intensity, etc.

1. Aspect ratio

It is the ratio of the width to the height of the bounding rectangle of the object .

x,y,w,h = cv.boundingRect(cnt)
aspect_ratio = float(w)/h

2. area

Extent is the ratio of the contour area to the bounding rectangle area .

area = cv.contourArea(cnt)
x,y,w,h = cv.boundingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area

3. Firmness

Solidity is the ratio of the area of ​​the contour to the area of ​​its convex hull .

area = cv.contourArea(cnt)
hull = cv.convexHull(cnt)
hull_area = cv.contourArea(hull)
solidity = float(area)/hull_area

4. Equivalent diameter

Equivalent diameter is the diameter of a circle having the same area as the contour area.

area = cv.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)

5. Orientation

Orientation is the angle at which an object is pointing . The following method also gives the lengths of the primary and secondary shafts.

mask = np.zeros(imgray.shape,np.uint8) cv.drawContours(mask,[cnt],0,255,-1) pixelpoints = np.transpose(np.nonzero(mask))</p> <h1>pixelpoints = cv.findNonZero(mask)</h1> <p>

6. Masks and [Pixels]

In some cases we may need all the points that make up the object . It can be done by following these steps:

leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

7. Maximum, minimum and their positions

We can find these parameters using the mask image.

min_val, max_val, min_loc, max_loc = cv.minMaxLoc(imgray,mask = mask)

8. Average Color or Average Intensity

Here, we can find the average color of the object. Or it can be the average intensity of the object in grayscale mode. We do this again with the same mask.

mean_val = cv.mean(im,mask = mask)

9. Extreme Points

Pole refers to the topmost, bottommost, rightmost, and leftmost points of an object.

leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

For example, if I apply this to a map of India, I get this result: 

Leave a Reply

Your email address will not be published.