opencv水果计数
时间: 2023-11-23 19:58:12 浏览: 175
opencv水果识别样本(苹果、香蕉、梨子)
以下是基于Pycharm编程平台与opencv开源库实现水果种类的简单识别与计数的步骤:
1. 导入必要的库和模块
```python
import cv2
import numpy as np
```
2. 读取图片并进行预处理
```python
img = cv2.imread('fruit.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
ret, thresh = cv2.threshold(blur, 60, 255, cv2.THRESH_BINARY)
```
3. 查找轮廓并绘制
```python
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
```
4. 计算水果数量
```python
fruit_count = len(contours)
print("水果数量为:", fruit_count)
```
5. 显示结果
```python
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文