stroke_focus_loss.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is refer from:
  16. https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/loss/stroke_focus_loss.py
  17. """
  18. import cv2
  19. import sys
  20. import time
  21. import string
  22. import random
  23. import numpy as np
  24. import paddle.nn as nn
  25. import paddle
  26. class StrokeFocusLoss(nn.Layer):
  27. def __init__(self, character_dict_path=None, **kwargs):
  28. super(StrokeFocusLoss, self).__init__(character_dict_path)
  29. self.mse_loss = nn.MSELoss()
  30. self.ce_loss = nn.CrossEntropyLoss()
  31. self.l1_loss = nn.L1Loss()
  32. self.english_stroke_alphabet = '0123456789'
  33. self.english_stroke_dict = {}
  34. for index in range(len(self.english_stroke_alphabet)):
  35. self.english_stroke_dict[self.english_stroke_alphabet[
  36. index]] = index
  37. stroke_decompose_lines = open(character_dict_path, 'r').readlines()
  38. self.dic = {}
  39. for line in stroke_decompose_lines:
  40. line = line.strip()
  41. character, sequence = line.split()
  42. self.dic[character] = sequence
  43. def forward(self, pred, data):
  44. sr_img = pred["sr_img"]
  45. hr_img = pred["hr_img"]
  46. mse_loss = self.mse_loss(sr_img, hr_img)
  47. word_attention_map_gt = pred["word_attention_map_gt"]
  48. word_attention_map_pred = pred["word_attention_map_pred"]
  49. hr_pred = pred["hr_pred"]
  50. sr_pred = pred["sr_pred"]
  51. attention_loss = paddle.nn.functional.l1_loss(word_attention_map_gt,
  52. word_attention_map_pred)
  53. loss = (mse_loss + attention_loss * 50) * 100
  54. return {
  55. "mse_loss": mse_loss,
  56. "attention_loss": attention_loss,
  57. "loss": loss
  58. }