用python 写个 图像轮廓查找的代码
时间: 2024-05-06 22:20:28 浏览: 5
以下是用Python编写的简单图像轮廓查找代码:
```
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), 3)
# 显示结果
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码将读取名为“image.jpg”的图像,将其转换为灰度图像,然后进行二值化处理。接着,使用`cv2.findContours()`函数查找图像中的轮廓,并将其绘制在原始图像上。最后,将结果显示出来。
请注意,该代码仅用于演示如何使用OpenCV执行图像轮廓查找任务。在实际应用中,可能需要进行更加复杂的处理,例如使用不同的轮廓近似算法,或者对轮廓进行进一步的分析和处理。
相关问题
写一段Python代码提取图像轮廓
下面是一段使用 OpenCV 库提取图像轮廓的 Python 代码:
```
import cv2
import numpy as np
# 读取图像
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用 Canny 边缘检测算法检测边缘
edges = cv2.Canny(gray, 50, 150)
# 查找图像中的轮廓
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原图上绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在代码中,首先我们读取了图像,并将其转换为灰度图。然后,使用 Canny 边缘检测算法检测图像中的边缘。最后,使用 `cv2.findContours()` 函数查找图像中的轮廓,并在原图上绘制出轮廓,最后显示结果图像。
对图像绘制轮廓写python代码
要对图像绘制轮廓,可以使用 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 函数将轮廓绘制在原图上,并显示图像。