• 图片去噪（去干扰点及干扰线）
• 将彩色图片二值化为黑白图片
• 图片字符切割
• 图片尺寸归一化
• 图片字符标记

1. 分量法
在rgb三个分量种按照需求选取一个分量作为灰度值
2. 最大值
选取rgb的最大值作为该pixel的灰度值
3. 平均值
g[i,j] = (r[i,j] + g[i,j] + b[i,j]) / 3,取rgb的平均值作为灰度值
4. 加权变换
由于人眼对绿色的敏感最高，对蓝色敏感最低，因此，按下式对RGB三分量进行加权平均能得到较合理的灰度图像。 L = R 299/1000 + G 587/1000 + B 114/1000 PIL 包中的Image.convert(‘L’) 就是采用的这种计算方式*

python代码如下：

``````#获取一个图片的自适应阈值
img_raw =  np.array(image)
width, height = image.size
ucThre = 0;
ucThre_new = 127;#该值初始不等于ucThre即可

while ucThre != ucThre_new:
nBack_count = 0
nData_count = 0
nBack_sum = 0
nData_sum = 0
for j in  range(height):
for i in range(width):
nValue = img_raw[j][i]
if nValue > ucThre_new:
nBack_sum += nValue
nBack_count+=1
else:
nData_sum += nValue
nData_count+=1
nBack_sum = nBack_sum / nBack_count
nData_sum = nData_sum / nData_count
ucThre = ucThre_new
ucThre_new = (nBack_sum + nData_sum) / 2
return math.ceil(ucThre_new)
``````

``````def get_bin_table(threshold=230):
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)

return table
``````

``````image = Image.open(img_path)
imgry = image.convert('L')  # 转化为灰度图
out = imgry.point(table, '1')
``````

``````# 图像处理-X像素投影法,0像素切割
def splitByPixel(image, text):
# img_raw = np.array(image)
w, h = image.size
splitCol = getSplit(image)

if len(splitCol) != len(text):
print("切割错误！", text)
return ""

for i in range(len(text)):
cropImg = image.crop((splitCol[i][0], 0, splitCol[i][1], h))
cropImg = resizeImge(cropImg, int(w / int(len(text))), h)  # 切割的图片尺寸不一，统一尺寸
char = text[i]
save_path = "./knnImage/letters/" + str(char) + "/" + str(uuid.uuid4()) + ".png"
cropImg.save(save_path)  # 保存切割下来的图片

# 获取切割列0像素切割
def getSplit(image):
img_raw = np.array(image)
w, h = image.size
allCol = []
for i in range(w):
allCol.append(i)
charCol = []
for i in range(w):
for j in range(h):
if img_raw[j][i] != True:
charCol.append(i)
break
# 找到0像素的列
zeroCol = [i for i in allCol if i not in charCol]
# 从0像素列中找出切割列
splitCol = []
col = zeroCol[1]
for vi, vv in enumerate(zeroCol):
tmparr = []
if vv < col + 4:
col += 1
else:
if vi > 0:
tmparr.append(zeroCol[vi - 1])
else:
tmparr.append(zeroCol[0])
tmparr.append(vv)
splitCol.append(tmparr)
col = vv

return splitCol
``````

``````def resizeImge(image,rew,reh):
img_raw = np.array(image)
w, h = image.size
top = 0
bottom =h
try:
for i in range (h):
for j in range(w):
if img_raw[i][j] != True:
top = i - 1
raise Getoutofloop()
except Getoutofloop:
pass

try:
for i in range(h):
for j in range(w):
if img_raw[h-1-i][j] != True:
bottom = h - i
raise Getoutofloop()
except Getoutofloop:
pass

cropImg = image.crop((0, top, w, bottom))
cropImg= cropImg.resize((rew,reh))

return cropImg

class Getoutofloop(Exception):
pass
``````