用python重新写一下
时间: 2023-06-30 18:27:32 浏览: 13
下面是用 Python 重写的代码:
```python
import cv2
img = cv2.imread('image.jpg')
if img is None:
print('Failed to read image!')
exit()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if area > 1000 and area < 5000:
cv2.drawContours(img, contours, i, (0, 255, 0), 2)
cv2.imshow('Result', img)
cv2.waitKey(0)
```
与 C++ 版本类似,使用 `cv2.threshold()` 函数对灰度图像进行二值化,然后使用 `cv2.findContours()` 函数提取轮廓,再通过遍历轮廓向量,使用 `cv2.contourArea()` 函数计算每个轮廓的面积,并判断是否在特定范围内。如果是,则通过 `cv2.drawContours()` 函数在图像上标记该轮廓。