在 Python 中使用 findContours 查找轮廓的方法如下:
- 使用 cv2.imread() 函数读取图像。
- 使用 cv2.cvtColor() 函数将图像转换为灰度图像。
- 使用 cv2.threshold() 函数对图像进行二值化处理。
- 使用 cv2.findContours() 函数查找图像中的轮廓。
示例代码如下:
import cv2
# 读取图像
img = cv2.imread("image.jpg")
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
# 显示图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
在这段代码中,首先读取了图像,然后将其转换为灰度图像,接着对图像进行二值化处理,最后使用 cv2.findContours() 函数查找图像中的轮廓。最后,使用 cv2.drawContours() 函数绘制轮廓,并使用 cv2.imshow() 函数显示图像。