把一张叫contours.png的图片用jupyter软件打出面积,周长,轮廓矩,轮廓的重心,轮廓的近似,轮廓的凸包,外接矩形,外接圆,椭圆拟合
时间: 2024-10-17 21:15:20 浏览: 25
在Jupyter中使用Python处理图像,可以利用`matplotlib`, `numpy`, `OpenCV`等库来获取图像的轮廓信息并计算相应的几何特征。这里是一个基本的步骤示例:
首先,确保已经安装了`matplotlib`, `numpy`, 和 `opencv-python` 库。如果没有,可以使用以下命令安装:
```bash
pip install matplotlib numpy opencv-python opencv-contrib-python
```
然后,在Jupyter notebook中,你可以这样做:
1. 导入必要的库:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
```
2. 加载图片:
```python
img = cv2.imread('contours.png', 0) # 读取灰度图
if img is None:
print("图片加载失败")
else:
# 图像二值化处理
_, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
```
3. 查找轮廓(contours):
```python
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
```
4. 计算区域(Area)、周长(Perimeter)、轮廓矩(Moments)、重心(Centroid):
```python
areas = [cv2.contourArea(c) for c in contours]
perimeters = [cv2.arcLength(c, True) for c in contours]
moments = [cv2.moments(c) for c in contours]
centroids = [(m['m10']/m['m00'], m['m01']/m['m00']) for m in moments if m['m00'] > 0] # 除以m00避免除以零错误
```
5. 凸包(Convex Hull)、近似(Approximation)、外接矩形(Bounding Rectangle):
```python
convex_hulls = [cv2.convexHull(c) for c in contours]
approximate_contours = [cv2.approxPolyDP(c, 0.01*cv2.arcLength(c, True), True) for c in contours]
# 获取每个轮廓的外接矩形和最小外接矩形
bounding_rects = [cv2.boundingRect(c) for c in contours]
min_bounding_rects = [cv2.minAreaRect(c) for c in contours]
```
6. 外接圆、椭圆拟合:
```python
circles = []
for contour in contours:
(x, y), radius = cv2.minEnclosingCircle(contour)
circles.append((int(x), int(y), int(radius)))
ellipses = []
for contour in contours:
ellipse = cv2.fitEllipse(contour)
ellipses.append(ellipse)
```
最后,展示结果(这一步可能会因Jupyter环境不同而略有差异):
```python
plt.figure(figsize=(10, 8))
for i, contour in enumerate(contours):
ax = plt.subplot(2, 4, i+1)
plt.imshow(thresh)
plt.plot(*zip(*convex_hulls[i].reshape(-1, 2)), 'r')
plt.title(f"Contour {i + 1}")
plt.axis('off')
plt.show()
```
阅读全文