opencv二值化
时间: 2023-06-30 09:24:22 浏览: 79
OpenCV中的二值化可以将一张灰度图像转化为只有黑白两种颜色的图像。二值化的目的是为了简化图像,便于后续的图像分析处理。在OpenCV中,可以通过cv2.threshold()函数来实现二值化。
具体代码和步骤如下:
1.将图像转化为灰度图像
```
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
2.进行二值化
```
ret, img_binary = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
```
其中,img_gray为灰度图像,127为阈值,255为最大值,cv2.THRESH_BINARY表示采用二值化的方式。
完整代码示例:
```
import cv2
img = cv2.imread('test.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_binary = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('binary', img_binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,test.jpg为待处理的图像。运行后,会显示二值化后的图像。
阅读全文
相关推荐












