当前位置:网站首页>[opencv learning] [contour detection]
[opencv learning] [contour detection]
2022-07-02 12:52:00 【A sea of stars】
Today, learn the contour detection method
import cv2
import numpy as np
# Show the image , Encapsulate as a function
def cv_show_image(name, img):
cv2.imshow(name, img)
cv2.waitKey(0) # Waiting time , In milliseconds ,0 Represents any key termination
cv2.destroyAllWindows()
# Function of edge detection
# cv2.findContours(img, mode, method)
# img: The input image , For high accuracy , It is recommended to use binary image
# mode: RETR_EXTERNAL( Only the outer contour is detected )、
# RETR_LIST( Detect all contours and keep the results to a List in )
# RETR_CCOMP, Detect all contours , And wrap the results in two layers , The first layer is the external outline of each part , The second layer is the inner boundary of the cavity
# RETR_TREE, Detect all contours , And reconstruct the hierarchy of nested contours
# RETR_LIST From an explanatory point of view , This should be the simplest . It just extracts all the contours , Without creating any parent-child relationship .
# RETR_EXTERNAL If you choose this mode , Only the outermost outline will be returned , All sub contours are ignored .
# RETR_CCOMP In this mode, all contours will be returned and divided into two levels of organizational structure .
# RETR_TREE In this mode, all contours are returned , And create a complete list of organizational structures . It will even tell you who is Grandpa , Dad , son , Grandson, etc .
# methord: Method of contour detection
# CHAIN_APPROX_NONE: With freeman Chain code output outline ,
# CHAIN_APPROX_SIMPLE: Keep only the end part , That is, only the end points are saved for horizontal, vertical and inclined lines . Less and more concise data .
img = cv2.imread('images/contour.png') # Turn to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Convert to binary image
cv_show_image('binary_src_img', threshold)
# contours, All contour information , It's a list structure
# hierarchy It's a hierarchy , It is also a structure that retains all results
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
print(len(contours))
print(type(contours))
draw_img = img.copy() # Copy an image , Keep the original image
# -1 It means that all the outlines are drawn , The last two parameters are the color and thickness of the outline ,drawContours It will be modified in place on the input image
res = cv2.drawContours(draw_img, contours, contourIdx=-1, color=(0, 255, 0), thickness=1)
cv_show_image('draw_contours_img', res)
# Features of contour
for i in range(len(contours)):
cont = contours[i]
print(' The first {} The area of the outline is {}, The circumference is {}', i, cv2.contourArea(cont), cv2.arcLength(cont, True)) # true Closed
# The outline is approximate
# There is a curve from point A point-to-point B, There is a connection AB, There is a point on the curve C,C The straight line AB Distance of d Maximum . If d <= A certain threshold , Then we can use AB Straight lines directly replace curves AB
# If d > A certain threshold , So you can't use another curve AB Straight line substituted , Then at this time, we have to put the curve AB Continue to divide into two sections , They are curves AC Sum curve CB. Try further
# Try further , See if this curve can be straight AC And straight lines CB Instead of . This is a divide and conquer / Recursively solve .
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
epsilon = 0.03 * cv2.arcLength(cont, True)
approx = cv2.approxPolyDP(cont, epsilon, True) # Find the approximation of the contour ,True It means closed
# Draw an approximate outline , Pass it on to drawContours The contour type of must be list
draw_img = cv2.drawContours(draw_img, [approx], contourIdx=-1, color=(0, 255, 0), thickness=1)
cv_show_image('approx_contours_img', draw_img)
# Outer rectangle
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
x,y,w,h = cv2.boundingRect(cont) # According to the contour, calculate the rectangular coordinates with the farthest circumscribed .
draw_img = cv2.rectangle(draw_img, pt1=(x,y), pt2=(x+w, y+h), color=(0, 255, 0), thickness=2) # Draw this rectangle , Will draw on the original picture
cv_show_image('rectangle_contours_img', draw_img)
# Circumcircle
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
(x,y), radius = cv2.minEnclosingCircle(cont) # Calculate the center and radius of the outermost circle according to the contour .
center = (int(x), int(y))
radius = int(radius)
draw_img = cv2.circle(draw_img, center=center, radius=radius, color=(0, 255, 0), thickness=2) # Draw this rectangle , Will draw on the original picture
cv_show_image('circle_contours_img', draw_img)
The original image is as follows :
Draw all the outlines :
The outline has internal outline and external outline , If you use mode = RETR_EXTERNAL Can only draw the outline
Draw all approximate outlines :
Draw the circumscribed largest rectangle of all contours
Draw the circumscribed maximum circle of all contours
边栏推荐
- Counting class DP acwing 900 Integer partition
- 线性DP AcWing 899. 编辑距离
- The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph
- 获取文件版权信息
- 深拷貝 事件總線
- Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
- Interview questions for software testing - a collection of interview questions for large factories in 2022
- 1380. Lucky numbers in the matrix [two-dimensional array, matrix]
- About wechat enterprise payment to change x509certificate2 read certificate information, publish to the server can not access the solution
- js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
猜你喜欢
Interval DP acwing 282 Stone merging
Ltc3307ahv meets EMI standard, step-down converter qca7005-al33 phy
JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
[ybtoj advanced training guide] similar string [string] [simulation]
通过反射执行任意类的任意方法
spfa AcWing 852. spfa判断负环
Analog to digital converter (ADC) ade7913ariz is specially designed for three-phase energy metering applications
Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
js2day(又是i++和++i,if语句,三元运算符,switch、while语句,for循环语句)
随机推荐
Sensor adxl335bcpz-rl7 3-axis accelerometer complies with rohs/weee
Linear DP acwing 896 Longest ascending subsequence II
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
获取文件版权信息
哈希表 AcWing 840. 模拟散列表
Redis bloom filter
Enhance network security of kubernetes with cilium
Bom Dom
PXE installation UOS prompt NFS over TCP not available from 10 x.x.x
Linear DP acwing 895 Longest ascending subsequence
浏览器node事件循环
3 A VTT端接 稳压器 NCP51200MNTXG资料
Variable, "+" sign, data type
Counter attack of flour dregs: MySQL 66 questions, 20000 words + 50 pictures in detail! A little six
C#运算符
阿里发布的Redis开发文档,涵盖了所有的redis操作
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
线性DP AcWing 896. 最长上升子序列 II
Analog to digital converter (ADC) ade7913ariz is specially designed for three-phase energy metering applications
Structured data, semi-structured data and unstructured data