python3.6.4opencv
时间: 2023-11-17 13:03:49 浏览: 139
以下是Python3.6.4和OpenCV3.4.0的一个例子,演示了如何使用Python和OpenCV检测图像中的物体并将物体裁剪下来:
```python
import cv2
import numpy as np
# step1:加载图片,转成灰度图
image = cv2.imread('example.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# step2:使用Canny算法进行边缘检测
edged = cv2.Canny(gray, 30, 200)
# step3:寻找轮廓
contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# step4:遍历轮廓,找到最大的轮廓
max_contour = None
max_area = 0
for contour in contours:
area = cv2.contourArea(contour)
if area > max_area:
max_area = area
max_contour = contour
# step5:在原图上绘制最大轮廓,并将其裁剪下来
mask = np.zeros_like(gray)
cv2.drawContours(mask, [max_contour], -1, 255, -1)
result = np.zeros_like(image)
result[mask == 255] = image[mask == 255]
# step6:显示结果
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文