Python要选定一个物体,测量它的周长,面积,角点
时间: 2023-05-31 10:05:24 浏览: 54
可以使用OpenCV库来实现。
首先,需要读入一张图片,并使用OpenCV提供的函数将其转换为灰度图像:
```python
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
接下来,可以使用Canny算法进行边缘检测:
```python
edges = cv2.Canny(gray, 50, 150)
```
然后,可以使用findContours函数找到轮廓:
```python
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
```
接下来,可以选择一个轮廓进行测量。可以通过绘制轮廓来选择:
```python
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这里,将轮廓绘制在原图上,并显示。可以通过观察图像来选择一个合适的轮廓。
选择好轮廓后,可以使用cv2.arcLength函数计算周长:
```python
cnt = contours[0]
perimeter = cv2.arcLength(cnt, True)
print('周长:', perimeter)
```
使用cv2.contourArea函数计算面积:
```python
area = cv2.contourArea(cnt)
print('面积:', area)
```
使用cv2.approxPolyDP函数计算角点:
```python
epsilon = 0.01 * perimeter
approx = cv2.approxPolyDP(cnt, epsilon, True)
print('角点:', len(approx))
```
在这里,使用了一个epsilon参数来控制近似精度。epsilon越小,近似结果越精确。
最后,可以将结果绘制在图像上并显示:
```python
cv2.drawContours(img, [approx], -1, (0, 0, 255), 3)
cv2.putText(img, 'C: {:.2f}'.format(perimeter), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.putText(img, 'A: {:.2f}'.format(area), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.putText(img, 'P: {}'.format(len(approx)), (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这里,将近似结果绘制在图像上,并使用cv2.putText函数将测量结果添加到图像中。最后,将图像显示出来。