基于opencv的水果识别
时间: 2023-12-10 09:34:52 浏览: 153
基于OpenCV的水果识别需要经过以下步骤:
1.读取图片并将其转换为HSV颜色空间。
```python
import cv2
image = cv2.imread("fruit.jpg")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
```
2.对图像进行中值滤波以去除噪声。
```python
hsv = cv2.medianBlur(hsv, 5)
```
3.使用inRange函数根据颜色范围创建掩膜。
```python
mask = cv2.inRange(hsv, (11, 43, 46), (25, 255, 255))
```
4.使用形态学操作进行开运算。
```python
line = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15), (-1, -1))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, line)
```
5.使用findContours函数查找图像中的轮廓。
```python
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
```
6.遍历轮廓并绘制矩形框。
```python
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
```
完整代码如下:
```python
import cv2
image = cv2.imread("fruit.jpg")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv = cv2.medianBlur(hsv, 5)
mask = cv2.inRange(hsv, (11, 43, 46), (25, 255, 255))
line = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15), (-1, -1))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, line)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("result", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文