前言
对灰度图二值化,当像素值高于阈值时,我们给这个像素赋予一个新值,否则我们给它赋予另外一种颜色。
ret,dst = threshold(src, thresh, maxval, type)
d
s
t
:
\color{orange}{dst:}
dst: 输出图
s
r
c
:
\color{orange}{src:}
src: 输入灰度图
t
h
r
e
s
h
:
\color{orange}{thresh:}
thresh:对像素值进行分类的阈值,常见为127
m
a
x
v
a
l
:
\color{orange}{maxval:}
maxval:当像素值高于(或小于,根据type决定)阈值时应该被赋予的新的像素值,一般为255
t
y
p
e
:
\color{orange}{type:}
type:阈值类型
- THRESH_BINARY 超过阈值部分取maxval,否则取0。举例说即>127的像素值取255(maxval的值),否则取0.
- THRESH_BINARY_INV 这里的INV指反转。对THRESH_BINARY的反转,即小于阈值部分的取maxval,否则取0。举例说即<127的像素值取255(maxval的值),否则取0。
- THRESH_TRUNC 大于阈值部分的设为阈值,否则不变。即截断值。
- THRESH_TOZERO 大于阈值部分不改变,否则设为0。
- THRESH_TOZERO_INV THRESH_TOZERO的反转,即大于阈值部分的设为0。
代码示例
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE) # 灰度模式读入图片
cv2.namedWindow('imshow', cv2.WINDOW_NORMAL) # 调整窗口大小
# cv2.imshow("imshow", img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
ret, thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]
for i in range(6):
# 使用函数 plt.subplot() 同时在一个窗口中显示多个图像
plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
效果图如下,可以对比效果图更直观的理解每个type的意思。