使用opencv-python计算苹果轮廓面积并绘制出轮廓
时间: 2024-05-02 14:22:08 浏览: 11
以下是使用opencv-python计算苹果轮廓面积并绘制出轮廓的代码:
```python
import cv2
# 读取图像
img = cv2.imread('apple.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)
# 计算轮廓面积
area = cv2.contourArea(contours[0])
# 绘制轮廓
cv2.drawContours(img, contours, 0, (0, 0, 255), 2)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 输出轮廓面积
print('Contour area:', area)
```
其中,`cv2.findContours()`函数用于查找图像中的轮廓,`cv2.contourArea()`函数用于计算轮廓面积,`cv2.drawContours()`函数用于绘制轮廓。在上述代码中,我们假设图像中只有一个苹果轮廓,因此直接使用`contours[0]`来计算轮廓面积和绘制轮廓。如果图像中有多个轮廓,则需要使用循环来依次计算每个轮廓的面积和绘制每个轮廓。