给出图像二值化处理python代码
时间: 2023-09-08 11:14:36 浏览: 51
以下是一段简单的图像二值化处理的Python代码:
```
import cv2
img = cv2.imread('input_image.jpg', 0) # 读取灰度图像
ret, thresh_image = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # 阈值设为127,超过阈值的像素点设置为255(白色),反之设置为0(黑色)
cv2.imshow('Binary Image', thresh_image) # 显示二值化图像
cv2.waitKey(0) # 等待按键事件
cv2.destroyAllWindows() # 关闭所有窗口
```
说明:
- cv2.imread()函数用于读取图像,参数0表示将图像读取成灰度图像。
- cv2.threshold()函数用于二值化图像,第一个参数为输入图像,第二个参数为设定的阈值,第三个参数为超过阈值的像素点设定的值,第四个参数为低于阈值的像素点设定的值。
- cv2.imshow()函数用于显示图像,第一个参数为窗口名,第二个参数为要显示的图像。
- cv2.waitKey()函数等待键盘事件,0表示无限等待。
- cv2.destroyAllWindows()函数用于关闭所有窗口。
相关问题
图像二值化处理python
以下是使用Python进行图像二值化处理的示例代码:
1. 导入必要的库
```python
import cv2
import numpy as np
```
2. 读取图像
```python
img = cv2.imread('image.jpg', 0) # 以灰度模式读取图像
```
3. 阈值化处理
```python
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
```
这里的阈值为127,如果像素值大于阈值,则设置为最大值255,否则设置为0。
4. 显示处理后的图像
```python
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg', 0)
# 阈值化处理
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 显示处理后的图像
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在使用cv2.imshow()函数时,窗口名称必须是字符串类型,否则会报TypeError错误。
图像二值化代码python
以下是一个简单的图像二值化代码的Python实现:
```
import cv2
# 读取原始图像
img = cv2.imread('image.jpg', 0)
# 图像二值化处理
ret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 显示二值化后的图像
cv2.imshow('Binary Image', binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码使用的是OpenCV库,将原始图像读取后,调用cv2.threshold()函数进行二值化处理。如果像素值大于阈值127,则将像素值设置为255,否则设置为0。最后显示二值化后的图像。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)