OpenCV-Python drawn contour detection rectangular frame (findContours \ boundingRect \ rectangle)

Article directory
1 acquires the contour
1.1 Return Value: Image, Contours, Hierarchy
2 depicts the profile
3 acquires the contour region
4 outside the minimum matrix obtaining object
1 acquires the profile
OpenCV2 acquired profile is mainly used cv2.findContours ()
 

import cv2

img = cv2.imread('wujiaoxing.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

_,contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

draw_img0 = cv2.drawContours(img.copy(),contours,0,(0,255,255),3)
draw_img1 = cv2.drawContours(img.copy(),contours,1,(255,0,255),3)
draw_img2 = cv2.drawContours(img.copy(),contours,2,(255,255,0),3)
draw_img3 = cv2.drawContours(img.copy(), contours, -1, (0, 0, 255), 3)


print ("contours:类型:",type(contours))
print ("第0 个contours:",type(contours[0]))
print ("contours 数量:",len(contours))

print ("contours[0]点的个数:",len(contours[0]))
print ("contours[1]点的个数:",len(contours[1]))

cv2.imshow("img", img)
cv2.imshow("draw_img0", draw_img0)
cv2.imshow("draw_img1", draw_img1)
cv2.imshow("draw_img2", draw_img2)
cv2.imshow("draw_img3", draw_img3)

cv2.waitKey(0)
cv2.destroyAllWindows()

输出:
contours:类型: <class 'list'>
第0 个contours: <class 'numpy.ndarray'>
contours 数量: 3
contours[0]点的个数: 6
contours[1]点的个数: 74

Wherein, cv2.findContours () a second main parameters

cv2.RETR_LIST: contour detection is not established hierarchical relationship
cv2.RETR_TREE: L establish a profile of a hierarchical tree structure.
cv2.RETR_CCOMP: establish two levels of the contour, the outer boundary of the top layer, which layer is well within the boundary information.
cv2.RETR_EXTERNAL: indicates detects only the outer contour
cv2.findContours () method of the third parameter of the approximate contour approaches

cv2.CHAIN_APPROX_NONE store all contour points, two points adjacent to the pixel position of the difference does not exceed 1, i.e., max (ABS (X1-X2), ABS (Y2-Y1)) ==. 1
cv2.CHAIN_APPROX_SIMPLE compression in the horizontal direction, the vertical direction, a diagonal direction of the element, leaving only the coordinates of the end point direction, for example, a rectangular profile only 4 points to save the profile information
cv2.CHAIN_APPROX_TC89_L1, CV_CHAIN_APPROX_TC89_KCOS using teh-Chinl chain approximation algorithms
1.1 return value: image, contours , Hierarchy
contour return value
cv2.findContours () function returns a first list, list element is a profile of each image, represented by the numpy ndarray.
hierarchy return value
of the function also returns an optional hiararchy result, which is a ndarray, wherein the number of elements and the same number of contours, each contour contours [i] corresponding to the four elements hierarchy hierarchy [i] [0] ~ hierarchy [i] [3] , respectively, a rear profile, a front profile, the parent profile, the index number embedded profile, if no corresponding entry, then the value is negative.
2 depicts the profile
cv2.drawContours () function
cv2.drawContours (image, contours, contourIdx, color [, thickness [, lineType [, hierarchy [, maxLevel [, offset]]]]])

The first parameter is indicated on the drawn contour which image;
second parameter is the profile itself, is a list in Python.
The third parameter specifies which of contouring strip profile list, if it is -1, which draw all contour. The latter parameter is simple. Wherein the thickness indicates that the width of the contour line, if it is -1 (cv2.FILLED), was filled mode. Drawing parameters after independence in detail.
To see for yourself what drew the outline, you can use cv2.boundingRect () function to get the outline of the range, namely the upper left corner origin, as well as his high and wide. Then cv2.rectangle () method to draw a rectangular profile

"""
x, y, w, h = cv2.boundingRect(img)   
    参数:
    img  是一个二值图
    x,y 是矩阵左上点的坐标,
    w,h 是矩阵的宽和高

cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
    img:       原图
    (x,y):   矩阵的左上点坐标
    (x+w,y+h):是矩阵的右下点坐标
    (0,255,0): 是画线对应的rgb颜色
    2:         线宽
"""
for i in range(0,len(contours)):  
    x, y, w, h = cv2.boundingRect(contours[i])   
    cv2.rectangle(image, (x,y), (x+w,y+h), (153,153,0), 5) 



3 get contour area

new_image=image[y+2:y+h-2,x+2:x+w-2]    # 先用y确定高,再用x确定宽
input_dir=("E:/cut_image/")
if not os.path.isdir(input_dir):
    os.makedirs(input_dir)
cv2.imwrite( nrootdir+str(i)+".jpg",newimage) 
print (i)


4 Minimum ambient obtaining object matrix
used cv2.minAreaRect (cnt), returns the smallest point set cnt circumscribed rectangle, is a set of points cnt array or vector of the required minimum bounding rectangle, the number of the variable set point.
Wherein: cnt = np.array ([[x1 , y1], [x2, y2], [x3, y3], [x4, y4]]) # must be in the form of an array of array

rect = cv2.minAreaRect (cnt) # give minimum bounding rectangle (center (x, y), (width, height), rotation angle)
box = np.int0 (cv2.boxPoints (RECT)) will be a rectangular box by # frame

 

Published 86 original articles · won praise 267 · Views 1.77 million +

Guess you like

Origin blog.csdn.net/javastart/article/details/104348348