python 图像处理,,cv2.thresh


cv2.threshold介绍,如下图所示,每个数字代表起本身的灰度值大小

技术分享

cv2.threshod接收5种类参数形式,分别是cv2.THRESH_BINARY,cv2.THRESH_BINARY_INV,cv2.THRESH_TRUNC ,cv2.THRESH_TOZERO,cv2.THRESH_TOZERO_INV

(1)THRESH_BINARY(Binary Thresholding)

# Binary Threshold,原图像素>阈值,该像素点的值保持不变,否则为0.即大于阈值的部分变成像素最大值,小于阈值的部分变为0if src(x,y) > thresh  dst(x,y) = maxValueelse  dst(x,y) = 0

(2)THRESH_BINARY_INV(Inverse Binary Thresholding)

# Inverse Binary Threshold,原图像素<阈值,该像素点的值为0,否则保持不变.与(1)相反,大于阈值的部分变为0,小于阈值的部分变成像素最大值if src(x,y) > thresh  dst(x,y) = 0else  dst(x,y) = maxValue

(3)THRESH_TRUNC(TruncateThresholding)

# Truncate Threshold,原图像素>阈值,该像素点的值等于阈值,否则保持不变.即,将所有像素变成阈值以下水平if src(x,y) > thresh  dst(x,y) = threshelse  dst(x,y) = src(x,y)

(4)THRESH_TOZERO(Threshold to Zero)

# Threshold to Zeroif src(x,y) > thresh  dst(x,y) = src(x,y)else  dst(x,y) = 0

(5)THRESH_TOZERO_INV(Inverted Threshold to Zero)

# Inverted Threshold to Zeroif src(x,y) > thresh  dst(x,y) = 0else  dst(x,y) = src(x,y)

以上图为例,python代码为:

‘‘‘     OpenCV Threshold Example  Copyright 2015 by Satya Mallick <spmallick@gmail.com>‘‘‘# import opencv import cv2 # Read image src = cv2.imread("threshold.png", cv2.IMREAD_GRAYSCALE); # Basic threhold example th, dst = cv2.threshold(src, 0, 255, cv2.THRESH_BINARY); cv2.imwrite("opencv-threshold-example.jpg", dst); # Thresholding with maxValue set to 128th, dst = cv2.threshold(src, 0, 128, cv2.THRESH_BINARY); cv2.imwrite("opencv-thresh-binary-maxval.jpg", dst); # Thresholding with threshold value set 127 th, dst = cv2.threshold(src,127,255, cv2.THRESH_BINARY); cv2.imwrite("opencv-thresh-binary.jpg", dst); # Thresholding using THRESH_BINARY_INV th, dst = cv2.threshold(src,127,255, cv2.THRESH_BINARY_INV); cv2.imwrite("opencv-thresh-binary-inv.jpg", dst); # Thresholding using THRESH_TRUNC th, dst = cv2.threshold(src,127,255, cv2.THRESH_TRUNC); cv2.imwrite("opencv-thresh-trunc.jpg", dst); # Thresholding using THRESH_TOZERO th, dst = cv2.threshold(src,127,255, cv2.THRESH_TOZERO); cv2.imwrite("opencv-thresh-tozero.jpg", dst); # Thresholding using THRESH_TOZERO_INV th, dst = cv2.threshold(src,127,255, cv2.THRESH_TOZERO_INV); cv2.imwrite("opencv-thresh-to-zero-inv.jpg", dst); 

结果图:

技术分享技术分享技术分享

(1) (2) (3)

技术分享技术分享

(4) (5)
参考连接:

http://www.learnopencv.com/opencv-threshold-python-cpp/

http://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html

python 图像处理

评论关闭