图像分割有多种形式。 聚类、压缩、边缘检测、区域增长、图分区、分水岭等等;(Clustering. Compression. Edge detection. Region-growing.
Graph partitioning. Watershed. The list goes on.)
但是最开始只有最基本的一种:就是本文中介绍的 threholding 阈值化
一定要尝试设置thresh,因为它会根据您提供的thresh值给出不同的结果。
参考:Thresholding: Simple Image Segmentation using OpenCV
cv2.threhold 函数签名:
(T,threshImage)= cv2.threshold(src,thresh,maxval,type)
参数:
- src:源图像,或我们要对其执行阈值处理的图像。此图像应为灰度。
- thresh:阈值,用于对灰度图像中的像素强度进行分类。
- maxval:方法种用到的阈值;
- type: 要使用的阈值方法。可以为:
cv2.THRESH_BINARY
cv2.THRESH_BINARY_INV
cv2.THRESH_TRUNC
cv2.THRESH_TOZERO
cv2.THRESH_TOZERO_INV
1. cv2.THRESH_BINARY 超过阈值的像素设置为maxVal,不超过的设置为0
2. cv2.THRESH_BINARY_INV 1的反转(不超过阈值的像素设置为maxVal,超过的设置为0)
3. cv2.THRESH_TRUNC 超过阈值的设为thresh
4. cv2.THRESH_TOZERO 低于阀值的设为0
5. cv2.THRESH_TOZERO_INV (低于阀值的设为maxVal)
返回值:
- T: 用于阈值化的值,同thresh
- threshImage: 阈值化后生成的图像
原图:
# python threshold.py --image images/skateboard_decks.png --threshold 245
import argparse
import cv2
# --image 是我们要阈值的图像的路径。
# --threhold 是将要传递到cv2.threshold的阈值
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="Path to the image to be thresholded")
ap.add_argument("-t", "--threshold", type=int, default=128,
help="Threshold value")
args = vars(ap.parse_args())
# 加载图片并灰度化【 转换为灰度,期望一个单通道图像。】
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 定义我们的阈值方法列表
methods = [
("THRESH_BINARY", cv2.THRESH_BINARY),
("THRESH_BINARY_INV", cv2.THRESH_BINARY_INV),
("THRESH_TRUNC", cv2.THRESH_TRUNC),
("THRESH_TOZERO", cv2.THRESH_TOZERO),
("THRESH_TOZERO_INV", cv2.THRESH_TOZERO_INV)]
# 遍历阈值方法
for (threshName, threshMethod) in methods:
# 将255(白色)作为阈值测试时的值作为第三个参数
(T, thresh) = cv2.threshold(gray, args["threshold"], 255, threshMethod)
cv2.imshow(threshName, thresh)
cv2.waitKey(0)