基于图像的苹果坏果检测代码opencv缺陷检测
时间: 2023-06-15 21:06:00 浏览: 83
以下是一个基于OpenCV的苹果坏果检测的代码示例:
```python
import cv2
import numpy as np
# 加载图像
img = cv2.imread('apple.jpg')
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对灰度图像进行高斯模糊
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 使用自适应阈值进行二值化
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# 执行形态学操作以去除噪声和填充空洞
kernel = np.ones((3, 3), np.uint8)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=3)
# 查找轮廓并绘制边界框
contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w*h > 500: # 过滤掉过小的轮廓
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个代码会将苹果的缺陷以绿色的边界框的形式标出来。你可以根据自己的需求进行修改和优化。