# 验证码识别之二值化

## 前言

### 迭代法

1. 求出图像中的最小灰度值和最大灰度值，分别记为Gmin和Gmax,则阈值初值T0=(Gmin+Gmax)/2;
2. 根据阈值T0将图像分割成前景和背景两部分，求出两部分的平均灰度值m1和m2,平均灰度值=总灰度值/像素个数
3. 求出新阈值T1=(m1+m2)/2
4. 如果T0=T1，则结束，否则将T1的值赋予T0，从第2步重新计算。

``````import numpy as np
from PIL import Image

def iteration(img_path):
img = Image.open(img_path).convert('L')
a = np.array(img)
a = a.ravel()
k = int((int(a.max()) + int(a.min()))/2) # 即初始阈值T0
m = -1
while k != m:
# C1和C2为前景和背景的像素
C1 = a[a >= k]
C2 = a[a < k]
k = m
m1 = np.sum(C1)/len(C1) if len(C1) else 0
m2 = np.sum(C2)/len(C2) if len(C2) else 0
m = int((m1 + m2)/2)
return k ``````

### 最大类间方差法(OTSU)

`p1*m1+p2*m2=mG ``p1+p2=1 ` 则类间方差表达式为：

``````import numpy as np
from PIL import Image

def otsu(img_path):
img = Image.open(img_path).convert('L')
a = np.array(img)
a = a.ravel()
L = []
for k in range(0, 256):
C1 = a[a >= k]
C2 = a[a < k]
if not(len(C1) and  len(C2)):
L.append(0)
continue
m1 = np.sum(C1)/len(C1)
m2 = np.sum(C2)/len(C2)
p1 = len(C1)/len(a)
p2 = len(C2)/len(a)
x = p1 * p2 * (m1 - m2) * (m1 - m2)
L.append(x)
return L.index(max(L))``````