前言
AI玩游戏的一点尝试(1)------ 架构设计与初步状态识别
AI玩游戏的一点尝试(2)------ 初探无监督学习与特征可视化
数据采集
养成过程中的训练加值是以+XX的形式表示的,我希望模型可以忽略+号,直接输出数字结果。
之前的数字在屏幕上是常驻显示的,而这种数字不是。这里有两种思路:训练一个模型专门用于判断区域内是否有数字;或者使用现有数字识别模型的全空表示没有数字。先使用现有模型试试看。

和之前一样编辑模板后裁剪区域:

但是这次有不存在数字的数据,即使有数字也有+号干扰ocr识别。

查看大量ocr输出结果后发现,ocr对于数字部分依然可以较为准确的识别,对于+号和噪点会识别为汉字,因此通过提取数字的方式可以较为准确的得到识别结果。
进一步观察结果后发现,score>0.5的结果相对而言比较准确。
python
ocr_result = ocr.ocr.ocr_for_single_line(np.array(cropped_img))
# print(ocr_result)
if ocr_result['score'] >= 0.5:
continue
ocr_text = ocr_result['text']
digit_chars = []
for char in ocr_text:
if char.isdigit():
digit_chars.append(char)
if digit_chars:
digit = int(''.join(digit_chars))
else:
digit = ""
模型优化
初步训练后的误差较大,于是寻找优化方法。
随后发现不同区域的宽高比并不相同,在考虑保持宽高比进行填充是否比直接拉伸要更好:

python
class ResizeWithPadding:
def __init__(self, target_size, fill=0):
self.target_height, self.target_width = target_size
self.fill = fill
def __call__(self, img):
# 获取原始尺寸
width, height = img.size
# 计算缩放比例,保持宽高比
scale = min(self.target_width / width, self.target_height / height)
# 计算新尺寸
new_width = int(width * scale)
new_height = int(height * scale)
# resize保持宽高比
img = F.resize(img, (new_height, new_width))
# 创建目标尺寸的画布并居中放置
new_img = Image.new(img.mode, (self.target_width, self.target_height), self.fill)
paste_x = (self.target_width - new_width) // 2
paste_y = (self.target_height - new_height) // 2
new_img.paste(img, (paste_x, paste_y))
return new_img
再经过灰度调整,重新计算数据集的均值和标准差:
python
def calculate_mean_std_grayscale(dataloader):
mean = torch.zeros(1)
std = torch.zeros(1)
total_images = 0
logger.info("计算灰度图均值...")
for images in tqdm(dataloader):
batch_mean = torch.mean(images, dim=[0, 2, 3])
mean += batch_mean * images.size(0)
total_images += images.size(0)
mean /= total_images
logger.info("计算灰度图标准差...")
for images in tqdm(dataloader):
batch_var = torch.mean((images - mean.view(1, 1, 1, 1)) ** 2, dim=[0, 2, 3])
std += batch_var * images.size(0)
std = torch.sqrt(std / total_images)
return mean, std
根据置信度强化数据集
经过优化后,依然有小部分识别容易出错(比如17混淆、79混淆、38混淆等),观察发现此时结果的置信度通常较低,于是优化脚本在置信度低时进行保存:
python
if min_confidence < 0.9:
filename = f"data/predict_digit/{result['value']}_{timestamp_str}_{min_confidence:.2f}_{attribute}.png"
img_bgr = cv2.cvtColor(processed_images[attribute], cv2.COLOR_RGB2BGR)
img_pil = Image.fromarray(img_bgr)
img_pil.save(filename)
玩一段时间后,打开保存的文件夹人工校对标注后加入数据集重新训练,可以不断优化训练效果。
成果
还有一种数字也一样进行识别和标注,这样数字识别模型就可以较为准确的同时识别三种不同样式的数字了:

下一步
游戏中除了直接显示的数字以外,还有很多进度条、状态等需要辨别,下一步处理这方面的输入。