Image outline of OpenCv

Table of contents

1. Definition of Image Contour

2. Draw the outline

3. Calculate the contour area and perimeter


1. Definition of Image Contour

Image contours are continuous bands of the same color or grayscale. Contours are useful in shape analysis and object detection and recognition

The role of the outline:

  • for graphic analysis
  • Object Recognition and Detection

important point:

  • For the accuracy of detection, it is necessary to perform binarization or Canny operation on the image first
  • Outlining will modify the input image. If you want to continue using the original image later, you should store the original image in another variable.

The case code is as follows:

import cv2
import numpy as np

# 该图像显示效果是黑白的,但是实际上确实三个通道的彩色图像
img = cv2.imread('6.jpg')

# 变成单通道的黑白图片
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)

# 打印轮廓
print(contours)

# 释放资源
cv2.waitKey(0)
cv2.destroyAllWindows()

2. Draw the outline

Reference function:

 The code example is as follows:

import cv2
import numpy as np

# 该图像显示效果是黑白的,但是实际上确实三个通道的彩色图像
img = cv2.imread('6.jpg')

# 变成单通道的黑白图片
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)

# 打印轮廓
# print(contours)

# 绘制轮廓会直接修改原图
# 如果想保持原图不变,建议copy一份
img_copy = img.copy()
cv2.drawContours(img_copy,contours,-1,(0,0,255),2)

# 释放资源
cv2.waitKey(0)
cv2.destroyAllWindows()

3. Calculate the contour area and perimeter

Contour area refers to the area enclosed by all the pixels in each contour, the unit is pixel

The case code is as follows:

import cv2
import numpy as np

# 该图像显示效果是黑白的,但是实际上确实三个通道的彩色图像
img = cv2.imread('6.jpg')

# 变成单通道的黑白图片
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)

# 绘制轮廓会直接修改原图
# 如果想保持原图不变,建议copy一份
img_copy = img.copy()
cv2.drawContours(img_copy,contours,1,(0,0,255),2)

# 计算轮廓面积
area = cv2.contourArea(contours[1])

# 计算轮廓周长
perimeter = cv2.arcLength(contours[1],closed=True)

# 释放资源
cv2.waitKey(0)
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/weixin_64443786/article/details/131796588