使用大津法对原始图像二值化
时间: 2024-02-21 19:31:24 浏览: 103
大津法是一种二值化图像的方法,它可以自动确定二值化的阈值,使得图像的前景和背景能够被分离出来。
以下是使用Python实现大津法对原始图像进行二值化的示例代码:
```python
import cv2
# 读取原始图像
img = cv2.imread('test.jpg', 0)
# 大津法进行二值化
ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 显示处理结果
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上述代码中,cv2.threshold函数中的参数cv2.THRESH_BINARY + cv2.THRESH_OTSU表示使用大津法进行二值化。函数返回的阈值ret和二值化结果thresh分别表示自动计算出的二值化阈值和处理后的图像。
注意,在使用大津法进行二值化时,原始图像应该是灰度图像,并且需要提前进行灰度化处理。此外,大津法的优点是自适应性强,但在图像噪声较大的情况下可能产生误判,因此在实际应用中需要根据具体情况进行调整。
相关问题
VC 大津法图像二值化
### 使用 Visual C++ 实现大津法图像二值化
#### 大津法简介
大津法(Otsu's Method),也被称为最大类间方差法,是一种自动确定最佳阈值的方法。该方法通过最大化前景和背景之间的类间方差来找到最优的二值化阈值[^5]。
#### 开发环境配置
开发环境中需安装 Visual Studio 和 OpenCV 库。确保已正确设置项目属性以便能够调用 OpenCV 的库文件和头文件。
#### 示例代码实现
以下是使用 Visual C++ 结合 OpenCV 实现的大津法图像二值化的完整示例:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 加载原始灰度图片
Mat src = imread("path_to_image", IMREAD_GRAYSCALE);
if (src.empty()) {
cout << "Could not open or find the image!" << endl;
return -1;
}
// 创建窗口显示输入图像
namedWindow("Original Image", WINDOW_AUTOSIZE);
imshow("Original Image", src);
// 定义输出矩阵用于存储二值化后的结果
Mat binaryImage;
// 应用大津法进行自适应阈值处理
double otsuThreshVal = threshold(src, binaryImage, 0, 255, THRESH_BINARY | THRESH_OTSU);
// 输出计算得到的最佳阈值
printf("Optimal Threshold Value using Otsu's method is %f\n", otsuThreshVal);
// 显示二值化之后的结果图象
namedWindow("Binary Image via Otsu's Method", WINDOW_AUTOSIZE);
imshow("Binary Image via Otsu's Method", binaryImage);
waitKey(0); // 等待按键事件关闭所有打开的窗口
destroyAllWindows();
return 0;
}
```
此程序首先加载一张灰度模式下的源图像,并尝试对其进行二值化操作。`threshold()` 函数被用来执行实际的二值化工作,在这里指定了 `THRESH_OTSU` 参数让其采用大津算法寻找合适的阈值[^2]。
python大津法图像二值化
### 实现大津法(Otsu's Method)进行图像二值化
#### 导入必要的库
为了实现大津法,首先需要导入一些常用的Python库:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
#### 加载并预处理图像
加载待处理的灰度图像,并将其转换为NumPy数组形式以便后续操作。
```python
def load_image(image_path):
"""读取图片"""
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError("Image not found or unable to read.")
return image
```
#### 计算最佳阈值
通过遍历所有可能的阈值计算类间方差,找到使类间方差最大的那个作为最终的最佳分割阈值T*。
```python
def calculate_otsu_threshold(hist, total_pixels):
"""基于直方图数据计算Otsu阈值"""
current_max_variance = 0
threshold = 0
weight_background = 0.
sum_background = 0.
overall_mean_intensity = np.sum([i * hist[i] for i in range(len(hist))]) / total_pixels
for t in range(1, len(hist)):
# 更新背景区域权重和平均强度
weight_background += hist[t-1]
sum_background += (t-1) * hist[t-1]
if weight_background == 0: continue
mean_background = sum_background / weight_background
var_between_classes = weight_background * (1-weight_background) \
* ((mean_background - overall_mean_intensity)**2)
if var_between_classes > current_max_variance:
current_max_variance = var_between_classes
threshold = t
return threshold
```
#### 应用阈值得到二值化图像
利用之前求得的最佳阈值对原始输入图像执行简单的像素级比较运算完成二值化过程[^3]。
```python
def apply_threshold(image, T):
"""应用给定的阈值将图像转成二值图像"""
binary_image = np.where(image >= T, 255, 0).astype(np.uint8)
return binary_image
```
#### 完整流程函数封装
最后可以定义一个完整的函数来简化整个工作流:
```python
def otsu_binarization(image_path):
"""使用Otsu方法对指定路径下的图像做二值化处理."""
# Step 1: Load Image
gray_scale_image = load_image(image_path)
# Step 2: Compute Histogram and Total Pixels Count
histogram = cv2.calcHist([gray_scale_image],[0],None,[256],[0,256])
flattened_histogram = histogram.flatten()
num_of_total_pixels = np.sum(flattened_histogram)
# Step 3: Calculate Optimal Threshold Using Otsu's Method
optimal_threshold = calculate_otsu_threshold(flattened_histogram, num_of_total_pixels)
# Step 4: Apply the Found Threshold Value To Get Binary Output
result_binary_image = apply_threshold(gray_scale_image, optimal_threshold)
return result_binary_image, optimal_threshold
```
上述代码实现了从加载图像到最后得到二值化结果的一系列步骤。值得注意的是,在实际编程实践中可以直接调用OpenCV中的`cv2.threshold()`函数配合参数设置也可以轻松达成相同效果[^4]。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)