基于python写一个饮料瓶形状检测与识别的程序
时间: 2024-06-08 10:08:38 浏览: 137
要实现饮料瓶形状检测与识别,可以通过以下步骤实现:
1. 导入必要的python库和模块:
```
import cv2
import numpy as np
```
2. 读取饮料瓶图片:
```
img = cv2.imread('bottle.jpg')
```
3. 转换成灰度图:
```
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
4. 进行形态学变换,去除噪声:
```
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)
```
5. 边缘检测:
```
edges = cv2.Canny(opening, 50, 150, apertureSize=3)
```
6. 查找轮廓:
```
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
```
7. 遍历轮廓,筛选出符合条件的瓶子轮廓:
```
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt,True),True)
if len(approx)==4:
x,y,w,h = cv2.boundingRect(approx)
aspectRatio = float(w)/h
if aspectRatio > 0.7 and aspectRatio < 1.3:
cv2.drawContours(img,[approx],0,(0,255,0),3)
cv2.putText(img,'Bottle',(x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(0,255,0),2)
```
8. 显示结果:
```
cv2.imshow('Result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```
import cv2
import numpy as np
img = cv2.imread('bottle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)
edges = cv2.Canny(opening, 50, 150, apertureSize=3)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt,True),True)
if len(approx)==4:
x,y,w,h = cv2.boundingRect(approx)
aspectRatio = float(w)/h
if aspectRatio > 0.7 and aspectRatio < 1.3:
cv2.drawContours(img,[approx],0,(0,255,0),3)
cv2.putText(img,'Bottle',(x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(0,255,0),2)
cv2.imshow('Result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文