雙重閥值(Dual thresholding)

双重阈值(Dual thresholding)是一种将灰阶图像转化为二值黑白图像的技术。通过设定两个灰阶临界值T1和T2,像素值介于[T1, T2]的在转换后变为白色,其余则变为黑色。" 111841729,10295152,Swift中优化UITableView细胞高度计算,"['iOS开发', 'Swift', 'UITableView', '自动布局', '性能优化']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

雙重閥值(Dual thresholding):當灰階影像要轉換為二元黑白影像,對於影像的各個像素,先確定兩個灰階值T1與T2(臨界值),當像素灰階值 >= T1 & <= T2,則對應輸出影像的像素值設為1(白色),當其他像素灰階值,則對應輸出影像的像素值設為0(黑色)。
### 使用 OpenCV 获取图像二值化阈值 #### 方法一:基于最大熵法计算最优阈值 为了获得最佳的二值化效果,可以通过分析图像直方图来自动确定合适的阈值。一种常用的方法是采用最大熵算法寻找能够使前景与背景信息量最大的分隔点。 ```python import cv2 import numpy as np from skimage import exposure def get_otsu_threshold(image_path): img = cv2.imread(image_path, 0) # 读取灰度图片 _, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th2 image_path = 'example.jpg' binary_image = get_otsu_threshold(image_path) cv2.imshow('Binary Image', binary_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 此段代码实现了通过 Otsu 法求解全局最优阈值并完成二值化操作[^1]。 #### 方法二:自适应阈值处理 当待处理图像存在光照不均匀等问题时,可以考虑使用 `adaptiveThreshold()` 函数来进行局部区域内的动态阈值调整: ```python def adaptive_thresholding(image_path): img = cv2.imread(image_path, 0) # 自适应均值阈值化 adap_mean_thres = cv2.adaptiveThreshold( img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=11, C=2 ) # 自适应高斯加权平均阈值化 adap_gaussian_thres = cv2.adaptiveThreshold( img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blockSize=11, C=2 ) return adap_mean_thres, adap_gaussian_thres mean_thresh_img, gaussian_thresh_img = adaptive_thresholding(image_path) cv2.imshow('Adaptive Mean Thresholded Image', mean_thresh_img) cv2.imshow('Adaptive Gaussian Thresholded Image', gaussian_thresh_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 上述代码展示了两种不同类型的自适应阈值技术——分别是简单均值以及更复杂的高斯权重方案的应用实例。 对于简单的全局固定阈值设定,则可以直接调用 `threshold` 函数,并指定具体的阈值参数: ```python def simple_global_threshold(image_path, threshold_value): img = cv2.imread(image_path, 0) ret, thresh_img = cv2.threshold(img, threshold_value, 255, cv2.THRESH_BINARY) return thresh_img thresh_val = 127 # 用户定义的具体阈值 global_binary_image = simple_global_threshold(image_path, thresh_val) cv2.imshow('Global Binary Image', global_binary_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段程序片段说明了如何应用预设数值作为标准进行整个画面范围内的统一转换过程[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值