如何用cv2将图片黑色部分框出来
时间: 2024-03-23 12:39:16 浏览: 30
你可以使用cv2中的findContours函数来找到图像中的轮廓,然后使用drawContours函数将轮廓画出来。下面是一个示例代码:
```python
import cv2
# 读取图片并转为灰度图
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 将图像二值化,黑色部分变为纯黑色
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,cv2.threshold函数用于将灰度图像二值化,将黑色部分变为纯黑色,方便后面的轮廓查找。cv2.findContours函数用于查找轮廓,返回的是轮廓的坐标列表。cv2.drawContours函数用于将轮廓画在原图上,第三个参数-1表示绘制所有轮廓。最后,使用cv2.imshow函数显示图像,cv2.waitKey函数等待用户按下键盘任意键,cv2.destroyAllWindows函数关闭窗口。