对图像绘制轮廓写python代码
时间: 2023-07-22 08:17:21 浏览: 55
要对图像绘制轮廓,可以使用 OpenCV 库中的 findContours 和 drawContours 函数。下面是一个示例代码:
```
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, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上述代码中,首先读取一张图像并将其转为灰度图,然后进行二值化处理。接着使用 findContours 函数查找轮廓,返回轮廓的坐标点集合 contours 和层级关系 hierarchy。最后使用 drawContours 函数将轮廓绘制在原图上,并显示图像。
相关问题
对图像绘制轮廓写python代码 导包二值化阈值化阈值处理显示图像
好的,以下是示例代码:
```
import cv2
# 读取图像
img = cv2.imread('image.png')
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
代码中使用了 OpenCV 库进行图像处理和轮廓绘制,首先通过 `cv2.imread` 读取图像,然后使用 `cv2.cvtColor` 函数将图像转为灰度图。接下来使用 `cv2.threshold` 函数进行二值化处理,使用 `cv2.findContours` 函数查找图像中的轮廓,返回轮廓的坐标点集合 `contours` 和层级关系 `hierarchy`。最后使用 `cv2.drawContours` 函数将轮廓绘制在原图上,并使用 `cv2.imshow` 显示图像。
求二值图像的轮廓的python代码
以下是求二值图像轮廓的Python代码:
```python
import cv2
# 读取二值图像
img = cv2.imread('binary_image.png', cv2.IMREAD_GRAYSCALE)
# 提取轮廓
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示结果
cv2.imshow('contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:这个代码只适用于OpenCV 3及以上版本。如果你使用的是OpenCV 2,需要将第二个返回值改为contours。