python提取图片轮廓边缘检测加二值化
时间: 2023-10-03 19:02:06 浏览: 34
你可以使用OpenCV库来提取图片轮廓、进行边缘检测和二值化。下面是一个简单的代码示例:
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edged = cv2.Canny(gray, 30, 150)
# 二值化
threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# 提取轮廓
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 画出轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Edged Image', edged)
cv2.imshow('Threshold Image', threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码读取了一张名为 `image.jpg` 的图片,将其转换为灰度图像,进行边缘检测和二值化,并使用 `cv2.findContours()` 函数提取轮廓。最后,使用 `cv2.drawContours()` 函数将轮廓画在原始图像上,并显示结果。你可以根据自己的需求进行调整。