import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
输出图片
def show(img):
if img.ndim == 2:
plt.imshow(img,cmap='gray')
else:
plt.imshow(cv.cvtColor(img,cv.COLOR_RGB2BGR))
plt.show()
#1.直方图阈值
img = cv.imread('E:/DataSolve/mf2.jpg',0)
plt.hist(img.ravel(),256,[0,256])
plt.show()
_,img_bin = cv.threshold(img,125,255,cv.THRESH_BINARY)#125是阈值,255是设置的最大值
show(np.hstack([img,img_bin]))
#2.三角法阈值
th,img_bin = cv.threshold(img,0,255,cv.THRESH_TRIANGLE)
print(th)
show(np.hstack([img,img_bin]))
#迭代法阈值分割
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}")
#大津法阈值
th,img_bin = cv.threshold(img,-1,255,cv.THRESH_OTSU)
show(img_bin)
#自我实现大津法
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(th,T)
#自适应阈值分割
#opencv自带
img = cv.imread('E:/DataSolve/1.jpg',0)
img_adapt = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,21,6)
show(img_adapt)
#自己实现自适应阈值分割
#方法一
C = 6
winSize = 21
img_blur = cv.blur(img,(winSize,winSize))
img_bin1 = np.uint8(img>img_blur-C)*255
#方法二
alpha = 0.05
winSize = 21
img_blur = cv.GaussianBlur(img,(winSize,winSize),5)
img_bin = np.uint8(img>(1-alpha)*img_blur)*255
show(np.hstack([img_adapt,img_bin1,img_bin]))