imutils.grab_contours()
时间: 2024-06-12 17:09:26 浏览: 21
`imutils.grab_contours()` 是一个 OpenCV 工具包中的函数,它用于从图像中提取轮廓。
在使用 `findContours()` 函数查找图像中的轮廓后,`imutils.grab_contours()` 函数可以帮助我们处理不同版本的 OpenCV 返回的轮廓值。因为在不同版本的 OpenCV 中,返回的轮廓值可能是不同类型的变量(例如列表或元组),这使得我们在编写通用代码时可能会遇到问题。
`imutils.grab_contours()` 函数可以将返回的轮廓值转换为适当类型的列表,这样我们就可以方便地对其进行迭代和处理。
例如,我们可以使用以下代码来提取图像中的轮廓并绘制出来:
```python
import cv2
import imutils
# 加载图像
image = cv2.imread("image.jpg")
# 将图像转换为灰度
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对图像进行模糊处理
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 使用阈值化进行图像分割
_, thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)
# 查找图像中的轮廓
contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
# 在图像上绘制轮廓
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
# 显示图像
cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这样,使用 `imutils.grab_contours()` 函数后,我们就可以方便地处理轮廓并在图像上进行绘制。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)