物体尺寸测量python
时间: 2023-11-29 16:47:22 浏览: 108
以下是使用Python OpenCV实现测量图片物体宽度的步骤:
1.导入必要的库和模块
```python
import cv2
import numpy as np
```
2.读取图片并进行预处理
```python
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
ret, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
```
3.寻找轮廓并筛选出最大轮廓
```python
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = max(contours, key=cv2.contourArea)
```
4.绘制最大轮廓并计算物体宽度
```python
cv2.drawContours(img, [cnt], 0, (0, 255, 255), 2)
leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
width = rightmost[0] - leftmost[0]
```
5.显示结果并保存图片
```python
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('result.jpg', img)
```
阅读全文