目录
0 程序环境及所学函数
1 直方图阈值
2 三角法阈值
3 迭代法阈值及实现
4 大津法(otsu)阈值及实现
5 自适应阈值及实现
本章程序运行需要导入下面三个库,并定义了一个显示图像的函数
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def show(img):
if img.ndim == 2:
plt.imshow(img, cmap='gray')
else:
plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))
plt.show()
所学函数
直方图阈值
plt.hist(img.ravel(), 256, [0,256]) cv.threshold(img, th, 255, cv.THRESH_BINARY)
三角法阈值
th, img_bin = cv.threshold(img, th, 255, cv.THRESH_TRIANGLE)
大津法阈值
th, img_bin = cv.threshold(img, th, 255, cv.THRESH_OTSU)
自适应阈值分割
img_adapt = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 77, 0)
原理
threshold函数使
读入图像
img = cv.imread('pic/eagle500x500.jpg', 0)
show(img)
显示
程序实现
plt.hist(img.ravel(),256,[0,256]) #ravel拉平矩阵,数组降维
plt.show()
显示
plt.hist(img.flatten(),np.arange(-0.5,256,1),color='g')
plt.show()
显示
_,img_bin = cv.threshold(img,125,255,cv.THRESH_BINARY)#小于125置为0,大于125置为255
show(img_bin)
显示
原理
程序实现
# img = cv.imread('pic/blossom500x500.jpg', 0)
img = cv.imread('pic/eagle500x500.jpg', 0)
show(img)
plt.hist(img.flatten(), np.arange(-0.5, 256, 1), color='g')
plt.show()
显示
th, img_bin = cv.threshold(img, 0, 255, cv.THRESH_TRIANGLE)
print(th)
show(np.hstack([img, img_bin]))
显示
原理
程序实现
img = cv.imread('pic/eagle500x500.jpg', 0)
T = img.mean()
while True:
t0 = img[img < T].mean()
t1 = img[img >= T].mean()
t = (t0 + t1) / 2
if abs(T - t) < 1:
break
T = t
T = int(T)
print(f"Best threshold = {T}")
显示
原理
img = cv.imread('pic/eagle500x500.jpg', 0)
th, img_bin = cv.threshold(img, -1, 255, cv.THRESH_OTSU)
print(th)
show(img_bin)
显示
根据算法编程实现
img = cv.imread('pic/eagle500x500.jpg', 0)
Sigma = -1
T = 0
for t in range(0, 256):
bg = img[img <= t]
obj = img[img > t]
p0 = bg.size / img.size
p1 = obj.size / img.size
m0 = 0 if bg.size == 0 else bg.mean()
m1 = 0 if obj.size == 0 else obj.mean()
sigma = p0 * p1 * (m0 - m1)**2
if sigma > Sigma:
Sigma = sigma
T = t
print(f"Best threshold = {T}")
原理
编程实现
img = cv.imread('pic/page760x900.jpg', 0)
show(img)
显示
img_bin = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,
cv.THRESH_BINARY, 21, 6)
show(img_bin)
显示
自适应阈值分割实现
img = cv.imread('pic/page760x900.jpg', 0)
C = 6
winSize = 21
img_blur = cv.blur(img, (winSize, winSize))
img_bin = np.uint8(img > img_blur.astype(np.int) - C) * 255
show(img_bin)
显示
img = cv.imread('pic/page760x900.jpg', 0)
alpha = 0.05
winSize = 21
img_blur = cv.GaussianBlur(img, (winSize, winSize), 5)
img_bin = np.uint8(img > (1 - alpha) * img_blur) * 255
show(img_bin)
显示