用findcontours寻找最大轮廓
可以通过以下代码使用OpenCV的findContours函数来寻找最大轮廓:
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 将图像转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 寻找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大轮廓
max_contour = max(contours, key=cv2.contourArea)
# 在图像上绘制最大轮廓
cv2.drawContours(img, [max_contour], -1, (0, 255, 0), 2)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
在上面的代码中,首先读取图像,并将其转换为灰度图。然后使用cv2.threshold函数将图像二值化。接下来,使用cv2.findContours函数寻找所有的轮廓。最后,使用max函数和cv2.contourArea函数找到最大轮廓,并在原始图像上绘制它。
原文地址: https://www.cveoy.top/t/topic/bqXM 著作权归作者所有。请勿转载和采集!