stroke_focus_loss.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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[index]] = index
  36. stroke_decompose_lines = open(character_dict_path, "r").readlines()
  37. self.dic = {}
  38. for line in stroke_decompose_lines:
  39. line = line.strip()
  40. character, sequence = line.split()
  41. self.dic[character] = sequence
  42. def forward(self, pred, data):
  43. sr_img = pred["sr_img"]
  44. hr_img = pred["hr_img"]
  45. mse_loss = self.mse_loss(sr_img, hr_img)
  46. word_attention_map_gt = pred["word_attention_map_gt"]
  47. word_attention_map_pred = pred["word_attention_map_pred"]
  48. hr_pred = pred["hr_pred"]
  49. sr_pred = pred["sr_pred"]
  50. attention_loss = paddle.nn.functional.l1_loss(
  51. word_attention_map_gt, word_attention_map_pred
  52. )
  53. loss = (mse_loss + attention_loss * 50) * 100
  54. return {"mse_loss": mse_loss, "attention_loss": attention_loss, "loss": loss}