之前写过一篇one-hot编码,其中代码表示部分为字符与一维数组之间的转换。最近由tensorflow1切换到了tensorflow2,重写了一遍验证码训练,于是有了这次的字符与二维数组的转换。
一、字符串转换为二维数组
- 包含字符数MAX_CAPTCHA不变仍为4,同样字符取值范围CHAR_SET仍为1234567890十个数字。
- 使用numpy.zeros给定初始形状,会得到一个完全由0填充的二维数组

- 接下来与之前的一样,使用enumerate遍历数据
- 获取字符串的字符在取值范围中的索引
- 生成数组
二、二维数组转化为字符串
- 包含字符数MAX_CAPTCHA不变仍为4,同样字符取值范围CHAR_SET仍为1234567890十个数字。
- 首先设定一个初始值空字符串
- 使用enumerate遍历二维数组
- 由于one-hot编码只有1位有效其余为0,使用np.argmax查找其中的最大值,设置为索引
- 通过在取值范围中的索引获取字符,并与初始值连接
三、完整编码
import numpy as np
MAX_CAPTCHA = 4 # 最长4字符
CHAR_SET = '1234567890' # 验证码包括字符
def name2vec(picture_title):
vector = np.zeros([MAX_CAPTCHA, len(CHAR_SET)])
for index, item in enumerate(picture_title):
idx = CHAR_SET.index(item)
vector[index][idx] = 1
return vector
def vec2name(vector):
text = ''
for index, item in enumerate(vector):
idx1 = np.argmax(item)
text = text + CHAR_SET[idx1]
return text
if __name__ == '__main__':
vec = name2vec("1234")
print(vec)
name = vec2name(vec)
print(name)
运行结果: