使用 OpenCV 在图像中检测轮廓


在此程序中,我们将检测图像中的轮廓。轮廓可以简单地解释为连接具有相同颜色或强度的所有连续点的曲线。轮廓是形状分析、物体检测及识别中一种有用的工具。

原始图像

算法

Step 1: Import OpenCV.
Step 2: Import matplotlib.
Step 3: Read the image.
Step 4: Convert the image from bgr2rgb.
Step 5: Convert the rgb image to grayscale.
Step 4: Perform thresholding on the image.
Step 5: Find contours on the image.
Step 6: Draw contours on the image.
Step 7: Display the output.

示例代码

import cv2
import matplotlib.pyplot as plt

image = cv2.imread('testimage.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, binary = cv2.threshold(gray, 127,255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

image = cv2.drawContours(image, contours, -1, (0,255,0), 2)
plt.imshow(image)
plt.show()

输出

更新于:2021 年 3 月 17 日

649 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.