Contour detection + circumscribed rectangle (opencv+python)

1. Detection contour

contours, hierarchy = cv2.findContours(image,mode,method)
  • image: input image
  • mode: The mode of the outline.

cv2.RETR_EXTERNAL only detects the outer contour

The contour detected by cv2.RETR_LIST does not establish a hierarchical relationship

cv2.RETR_CCOMP establishes two-level contours, the upper layer is the outer boundary, and the inner layer is the boundary of the inner hole. If there is a connected object in the inner hole, the boundary of this object is also on the top layer

cv2.RETR_TREE creates an outline of a hierarchical tree structure.

  • method: The approximation method for the contour.

cv2.CHAIN_APPROX_NOME stores all contour points, and the pixel position difference between two adjacent points does not exceed 1; cv2.CHAIN_APPROX_SIMPLE compresses elements in the horizontal direction, vertical direction, and diagonal direction, and only retains the end point coordinates of this direction, such as one The rectangular contour only needs 4 points to save the contour information; cv2.CHAIN_APPROX_TC89_L1, cv2.CV_CHAIN_APPROX_TC89_KCOS

  • contours: the returned contours
  • hierarchy: attributes corresponding to each contour

2. Contour drawing

cv2.drawContours(image, contours, contourIdx, color, thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None)
  • image: input image
  • contours: image contour
  • contourIdx: Specifies which contour in the contour list to draw, if it is -1, all contours in it are drawn
  • color: the color of the line
  • thickness: the width of the line

3. Outer rectangle

rect = cv2.minAreaRect(contours)
  • contours: contour information
  • rect: The characteristic information of the rectangle, its structure is: rectangle center (x, y), (width, height), rotation angle.
points = cv2.boxPoints(rect)
points = np.int0(points)
  • rect: rectangular feature information
  • points: Get the four point coordinates of the smallest circumscribed rectangle
 image = cv2.drawContours(original, [points], 0, (0, 0, 255), 2)

4. Contour features

img = cv2.imread('图片位置')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
binary, contours, hierarchy = cv2.findContours(thresh, cv2RETR_TREE,cv2.CHAIN_APPROX_NONE)
cut = contours[0]
cv2.contourArea(cnt) #面积

cv2.arcLength(cnt,True) #周长,Ture表示闭合

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True) #轮廓近似

x,y,w,h = cv2.bonudingRect(cnt)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) #外接矩形

area = cv2.contourArea(cnt)
x,y,w,h = cv2.bonudingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area #轮廓面积与边界矩形比

Guess you like

Origin blog.csdn.net/qq_51377150/article/details/126178817