def main(path, save=False): # 获取切图标注,切图图片,原图图图片 all_mark_boxs, all_char_imgs, img_o = divImg(path, save) # 恢复模型,用于图片识别 model = cnn.create_model() model.load_weights('checkpoint/char_checkpoint') class_name = np.load('checkpoint/class_name.npy') # 遍历行 for i in range(0, len(all_char_imgs)): row_imgs = all_char_imgs[i] # 遍历块 for j in range(0, len(row_imgs)): block_imgs = row_imgs[j] block_imgs = np.array(block_imgs) # 图片识别 results = cnn.predict(model, block_imgs, class_name) print('recognize result:', results) # 计算结果 result = calculation(results) print('calculate result:', result) # 获取块的标注坐标 block_mark = all_mark_boxs[i][j] # 获取结果的坐标,写在块的最后一个字 answer_box = block_mark[-1] # 计算最后一个字的位置 x = answer_box[2] y = answer_box[3] iw = answer_box[2] - answer_box[0] ih = answer_box[3] - answer_box[1] # 计算字体大小 textSize = max(iw, ih) # 根据结果设置字体颜色 if str(result) == "√": color = (0, 255, 0) elif str(result) == "×": color = (255, 0, 0) else: color = (192, 192, 192) # 将结果写到原图上 img_o = cv2ImgAddText(img_o, str(result), answer_box[2], answer_box[1], color, textSize) # 将写满结果的原图保存 cv2.imwrite('imgs/question_result.png', img_o)详细解释每一行代码
时间: 2023-12-09 13:05:35 浏览: 71
deepzoom_tile.zip_deepzoom_tile_deep切图_切图脚本
该函数是主函数,用于调用其他函数完成图片切割、识别、计算和结果标注的功能。下面是每行代码的详细解释:
```python
def main(path, save=False):
```
定义主函数,传入参数为图片路径和是否保存中间结果。
```python
all_mark_boxs, all_char_imgs, img_o = divImg(path, save)
```
调用 `divImg` 函数,将图片切割成字符块,并返回切割后的字符块列表、字符图片列表和原图。
```python
model = cnn.create_model()
model.load_weights('checkpoint/char_checkpoint')
class_name = np.load('checkpoint/class_name.npy')
```
创建CNN模型并加载训练好的权重和字符类别名称。
```python
for i in range(0, len(all_char_imgs)):
row_imgs = all_char_imgs[i]
for j in range(0, len(row_imgs)):
block_imgs = row_imgs[j]
block_imgs = np.array(block_imgs)
results = cnn.predict(model, block_imgs, class_name)
print('recognize result:', results)
result = calculation(results)
print('calculate result:', result)
block_mark = all_mark_boxs[i][j]
answer_box = block_mark[-1]
x = answer_box[2]
y = answer_box[3]
iw = answer_box[2] - answer_box[0]
ih = answer_box[3] - answer_box[1]
textSize = max(iw, ih)
if str(result) == "√":
color = (0, 255, 0)
elif str(result) == "×":
color = (255, 0, 0)
else:
color = (192, 192, 192)
img_o = cv2ImgAddText(img_o, str(result), answer_box[2], answer_box[1], color, textSize)
```
遍历所有字符块,利用训练好的CNN模型识别字符,并利用 `calculation` 函数计算结果。然后获取字符块的标注坐标,计算结果的位置并将结果写到原图上。
```python
cv2.imwrite('imgs/question_result.png', img_o)
```
将写满结果的原图保存到本地。
阅读全文