当前位置:网站首页>Fundamentals of machine learning (5) image outline
Fundamentals of machine learning (5) image outline
2022-07-22 16:37:00 【@[email protected]】
Catalog
4 The area and perimeter of the contour
5 Polygon approximation and convex hull
1 What is image contour
An image outline is a curve of continuous points with the same color or gray scale . Contour is very useful in shape analysis and object detection and recognition .
Function of contour :
For graphic analysis
Object recognition and detection
Be careful :
In order to test the accuracy , You need to edit the image first Two valued or Canny operation .
When drawing the outline, the input image will be modified , If you want to continue using the original image later , The original image should be stored in other variables .
2 Find the outline
findContours(image, mode, method[, contours[, hierarchy[, offset]]])
mode Find the pattern of the contour
RETR_EXTERNAL = 0, Indicates that only the peripheral contour is detected
RETR_LIST = 1, The detected contour does not establish a hierarchical relationship , That is, detect all contours ,
RETR_CCOMP = 2, At most two levels per floor , From small to large , From inside to outside .
RETR_TREE = 3, Store the outline according to the tree , From big to small , From right to left . ( Commonly used )
method The contour approximation method is also called ApproximationMode
CHAIN_APPROX_NONE Save points on all contours
CHAIN_APPROX_SIMPLE, Save only corners , Like a quadrilateral , Keep only quadrilateral 4 Corner , Less storage information , Compare Commonly used
return contours and hierachy That is, outline and level ( You can also use the return value to receive )
3 Draw the outline
drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])
image Outline image to be drawn
contours Outline point ( from findContours Data found )
contourIdx The number of the outline to be drawn . -1 Means to draw all the contours
color Color of outline , Such as (0, 0, 255) It means red
thickness Line width , -1 Means to fill all
Code case :
import cv2
import numpy as np
# The image display effect is black and white , But it's actually 3 Color images of channels .
img = cv2.imread('./contours1.jpeg')
# Become a single channel black-and-white picture
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Two valued , Pay attention to it 2 Return values , Thresholds and results
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Contour search , The new version returns two results , Outline and hierarchy , The old version returns 3 Parameters , Images , Outline and hierarchy
result, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the outline , Be careful , Drawing the outline will change the original drawing
cv2.drawContours(img, contours, 1, (0, 0, 255), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
4 The area and perimeter of the contour
Contour area refers to the area surrounded by all pixels in each contour , In pixels .
Contour area is one of the important statistical characteristics of contour , The implicit information of each contour can be further analyzed by the size of the contour area , For example, distinguish the size of objects by contour area and recognize different objects .
After finding the contour , There may be many small outlines , We can filter by the area of the contour .
contourArea(contour)
contour Contour data
arcLength(curve, closed)
curve That is, contour
closed Whether it is a closed contour
Case code :
import cv2
import numpy as np
# The image display effect is black and white , But it's actually 3 Color images of channels .
img = cv2.imread('./contours1.jpeg')
# Become a single channel black-and-white picture
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Two valued , Pay attention to it 2 Return values , Thresholds and results
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Contour search , The new version returns two results , Outline and hierarchy , The old version returns 3 Parameters , Images , Outline and hierarchy
result, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the outline , Be careful , Drawing the outline will change the original drawing
cv2.drawContours(img, contours, 1, (0, 0, 255), 2)
# Calculated area
area = cv2.contourArea(contours[1])
print('area: ', area)
cv2.imshow('img', img)
# Circumference calculation
perimeter = cv2.arcLength(contours[1], True)
print('perimeter:', perimeter)
cv2.waitKey(0)
cv2.destroyAllWindows()
5 Polygon approximation and convex hull
findContours Contour information after contours May be too complex and not smooth , It can be used approxPolyDP Function to properly approximate the polygonal curve , This is it. Polygonal approximation of contour .
apporxPolyDP That is to say Polygon to approach contour , It's using Douglas-Peucker Algorithm ( In the method name DP)
DP The principle of the algorithm is relatively simple , The core is to constantly find the farthest point of the polygon and join it to form a new polygon , Until the shortest distance is less than the specified accuracy .
approxPolyDP(curve, epsilon, closed[, approxCurve])
curve The contour to be approximated
epsilon namely DP The threshold used by the algorithm threshold The smaller it is , The better the result.
closed Whether the contour is closed
The return value is the data of polygon approximation , utilize drawContours Just draw it .
Case study :
import cv2
import numpy as np
img = cv2.imread('./hand.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Two valued , Pay attention to it 2 Return values , Thresholds and results
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Contour search , The new version returns two results , Outline and hierarchy , The old version returns 3 Parameters , Images , Outline and hierarchy
result, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the outline , Be careful , Drawing the outline will change the original drawing
cv2.drawContours(img, contours, 0, (0, 0, 255), 2)
# Show the outline before polygon approximation
# Do polygon approximation , Returns a series of points on a polygon , That is, the outline after polygon approximation
approx = cv2.approxPolyDP(contours[0], 20, True)
# print(type(approx))
# print(approx)
# print('--------------------------------------')
# print(contours[0])
# Draw the outline of polygon approximation .
cv2.drawContours(img, [approx], 0, (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
6. convex hull
The approximation polygon is the height approximation of the contour , But sometimes , We want to use a convex polygon to simplify it . A convex hull is like an approximation polygon , It's just the convex polygon on the outermost layer of the object . Convex hull refers to the complete inclusion of the original contour , And a polygon composed only of points on the contour . Every part of a convex hull is convex , That is, the straight line connecting any two points in the convex hull is inside the convex hull . In the convex hull , The internal angle of any three consecutive points is less than 180°.
convexHull(points[, hull[, clockwise[, returnPoints]]])
points Contour data , from findContours obtain
colckwise Draw clockwise
Case code :
import cv2
import numpy as np
img = cv2.imread('./hand.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Two valued , Pay attention to it 2 Return values , Thresholds and results
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Contour search , The new version returns two results , Outline and hierarchy , The old version returns 3 Parameters , Images , Outline and hierarchy
result, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the outline , Be careful , Drawing the outline will change the original drawing
cv2.drawContours(img, contours, 0, (0, 0, 255), 2)
# Do polygon approximation , Returns a series of points on a polygon , That is, the outline after polygon approximation
approx = cv2.approxPolyDP(contours[0], 20, True)
# Draw the outline of polygon approximation .
cv2.drawContours(img, [approx], 0, (0, 255, 0), 2)
# Calculating convex hull
hull = cv2.convexHull(contours[0])
cv2.drawContours(img, [hull], 0, (255, 0, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
7. Outside rectangle
Circumscribed rectangle is divided into minimum circumscribed rectangle and maximum circumscribed rectangle .
The red rectangle in the figure below is the smallest circumscribed rectangle , The green rectangle is the largest circumscribed rectangle .
minAreaRect(points) Minimum circumscribed matrix
points That is, contour data findContours obtain
Return a tuple , The content is a rotating rectangle (RotatedRect) Parameters of : The starting coordinates of the rectangle x,y, The width and height of the rectangle , Selection angle of rectangle .
boundingRect(points) Maximum circumscribed matrix
points That is, contour data findContours obtain
Case code :
import cv2
import numpy as np
img = cv2.imread('./hello.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
result, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# The outermost outline is the whole image , contours[1] Represents the graphic outline in the image
# Notice that the returned content is a rotating rectangle , Contains the starting coordinates of the rectangle , Width, height and selection angle
(x, y), (w, h), angle = cv2.minAreaRect(contours[1])
print(x, y)
print(w, h)
print(angle)
r = cv2.minAreaRect(contours[1])
# Quickly rotatedrect Convert to contour data
box = cv2.boxPoints(r)
print(box)
# Contour must be an integer , It can't be a decimal , So convert it to an integer
box = np.round(box).astype('int64')
print(box)
# Draw the smallest circumscribed rectangle
cv2.drawContours(img, [box], 0, (255, 0, 0), 2)
# Returns the of a rectangle x,y and w,h
x,y, w, h = cv2.boundingRect(contours[1])
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
版权声明
本文为[@[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207220319486342.html
边栏推荐
- AT4379 [AGC027E] ABBreviate
- C# 上传图片至共享文件夹
- MySQL查询计划key_len如何计算
- Switch and router technology: Standard ACL, extended ACL and named ACL
- When the easycvr platform cascades, there is an error prompt. What is the reason why the port is unreachable?
- 博途PLC信号处理系列之卡尔曼滤波程序(Kalman Filter)
- Win10 系统一天蓝屏好多次,怎么解决?
- 【解决方案】解决ImportError: Library “GLU“ not found.问题
- ECCV 2022 | 修正FPN带来的大目标性能损害:You Should Look at All Objects
- 层序遍历BFS(广度优先)
猜你喜欢
The LAAS solution of elephant swap has risen rapidly and built a new defi2.0 protocol
Lecture 7 pipeline, environment variables and common commands
SFTP creation
The competition of trillion market value public chain is white hot. Is there still a chance for the new public chain?
stm32使用各种传感器的教程
Repair the problem of adding device groups and editing exceptions on easycvr platform
nested subqueries
Mock simulates data and initiates get and post requests (nanny level tutorials are sure to succeed)
What is SCM? What are the components of SCM?
[leetcode weekly race -- hash table number pairs] 6164. Maximum sum of digit and equal number pairs
随机推荐
Switch and router technology: Standard ACL, extended ACL and named ACL
Informatics Olympiad all in one 1977: [08noip popularization group] stereogram | Luogu p1058 [noip2008 popularization group] stereogram
Hybrid混合开发与JSBridge
Leetcode 234. palindrome linked list
层序遍历BFS(广度优先)
C # upload pictures to shared folder
JVM memory model: runtime data area and thread
Fastjson code execution cve-2022-25845
Transparent transmission of punctual atom Lora wireless serial port point-to-point communication and Its Precautions
Write a function in C language to delete the spaces in the string and return the number of spaces
AT5662 [AGC040D] Balance Beam(二分)
The two supply chain centers of HEMA launched the "background" of innovative research and development of multi format commodities
Classic books of Orthodontics
二叉树OJ题,IO题
计算机网络之DNS面试题
【解决方案】解决paddlepaddle运行强化学习代码时TypeError: fc() got an unexpected keyword argument ‘is_test‘的错误
[leetcode string -- string subscript sorting] 6121. Query the number with the smallest k after cutting the number
[ssm]ssm integration ③ (interface test)
Methods of checking the ranking of papers and periodicals
At5662 [agc040d] balance beam (two points)