使用python对图像中的轮廓最小包围圆圈进行截取
时间: 2023-07-14 08:12:23 浏览: 69
可以使用OpenCV库来实现对图像中轮廓最小包围圆圈的截取。具体步骤如下:
1. 使用OpenCV库读入图像,将其转换为灰度图像,并进行二值化处理。
```python
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
```
2. 使用OpenCV库的findContours函数找到图像中的轮廓,并使用drawContours函数将其绘制在原图上。
```python
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
```
3. 对于每个轮廓,使用minEnclosingCircle函数找到最小包围圆,并使用circle函数在原图上绘制出该圆。
```python
for contour in contours:
(x, y), radius = cv2.minEnclosingCircle(contour)
center = (int(x), int(y))
radius = int(radius)
cv2.circle(img, center, radius, (0, 255, 0), 2)
```
4. 对于每个最小包围圆,使用切片操作在原图上截取出其所包含的部分。
```python
for i, contour in enumerate(contours):
(x, y), radius = cv2.minEnclosingCircle(contour)
x, y, radius = int(x), int(y), int(radius)
crop = img[y - radius:y + radius, x - radius:x + radius]
cv2.imwrite('crop_{}.jpg'.format(i), crop)
```
完整代码如下:
```python
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
(x, y), radius = cv2.minEnclosingCircle(contour)
x, y, radius = int(x), int(y), int(radius)
crop = img[y - radius:y + radius, x - radius:x + radius]
cv2.imwrite('crop_{}.jpg'.format(i), crop)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```