赞
踩
OpenCV 提供了基于阈值的分割技术,这是一种简单且常用的图像分割方法,其基本思想是根据像素的灰度值将图像分为不同的区域。下面详细介绍了 OpenCV 中基于阈值的分割技术:
全局阈值分割(Global Thresholding):
cv2.threshold()
函数可用于执行全局阈值分割。你可以选择不同的阈值类型(如二进制阈值、反二进制阈值、截断阈值等)和阈值的取值。- import cv2
-
- # 读取图像
- image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
-
- # 全局阈值分割
- _, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
-
- # 显示分割结果
- cv2.imshow('Binary Image', binary_image)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
2.自适应阈值分割(Adaptive Thresholding):
cv2.adaptiveThreshold()
函数可用于执行自适应阈值分割。你需要指定分割方法、邻域大小和常数等参数。- import cv2
-
- # 读取图像
- image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
-
- # 自适应阈值分割
- binary_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
-
- # 显示分割结果
- cv2.imshow('Adaptive Binary Image', binary_image)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
3、Otsu's 二值化(Otsu's Binarization):
cv2.threshold()
函数结合 cv2.THRESH_OTSU
标志可以实现 Otsu's 二值化。- import cv2
-
- # 读取图像
- image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
-
- # Otsu's 二值化
- _, binary_image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
- # 显示分割结果
- cv2.imshow('Otsu Binary Image', binary_image)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。