generate_roi_imgs.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import argparse
  2. import os.path
  3. import cv2
  4. from PIL import Image, ImageDraw, ImageFont
  5. from tqdm import tqdm
  6. def generate_idcard(info_dir, save_dir):
  7. if not os.path.exists(save_dir):
  8. os.makedirs(save_dir)
  9. f1 = open('materials/rec_gt.txt', 'w+', encoding='utf-8')
  10. with open(info_dir, 'r', encoding='utf-8') as fp:
  11. text_lines = fp.readlines()
  12. cnt = 0
  13. for text_line in tqdm(text_lines):
  14. info = text_line.rstrip('\n').split(',')
  15. if cnt < len(text_lines) * 0.2:
  16. bg_path = "bgs/tw_idcard_bg_1.jpg"
  17. elif len(text_lines) * 0.2 <= cnt < len(text_lines) * 0.6:
  18. bg_path = "bgs/tw_idcard_bg_2.png"
  19. else:
  20. bg_path = "bgs/tw_idcard_bg_3.jpg"
  21. pil_image = Image.open(bg_path)
  22. # pil_image 接收住这个图片对象
  23. # width 为图片的宽, height为图片的高
  24. width, height = pil_image.size
  25. # 生成一张尺寸为 width * height 背景色为白色的图片
  26. bg = Image.new('RGB', (width, height), color=(0, 0, 0))
  27. bg.paste(pil_image, (0, 0)) # 写入底图
  28. # 第一个参数为图片
  29. # 第二个参数为图片的要从哪里开始写入,
  30. name = info[0] # 写入的文字
  31. content_name = name
  32. # print(name)
  33. name_font_size = 45
  34. temp_str = ''
  35. if len(name) <= 6:
  36. num_of_space = (2 * (6 - len(name)))/(len(name)-1)
  37. for i in range(0, len(name) - 1):
  38. temp_str += name[i]
  39. for j in range(0, int(num_of_space)):
  40. temp_str += ' '
  41. temp_str += name[len(name)-1]
  42. name = temp_str
  43. elif 6 < len(name) < 9:
  44. name_font_size = 35
  45. elif 9 <= len(name) <= 12:
  46. name_font_size = 25
  47. font = "./usedres/TW-Sung-98-1-2.ttf" # 一个字体文件
  48. name_font = ImageFont.truetype(font, name_font_size) # 设置名字字体和大小
  49. # 计算出要写入的文字占用的像素
  50. # 创建一个可以在给定图像上绘图的对象
  51. draw = ImageDraw.Draw(bg)
  52. draw.text((5, 0), name, fill="#07090E", font=name_font)
  53. # 保存画布
  54. img_path = save_dir + '/name_' + str(cnt) + '.png'
  55. f1.write(img_path + '\t' + content_name + '\n')
  56. cnt += 1
  57. bg.save(img_path, "PNG")
  58. f1.close()
  59. if __name__ == '__main__':
  60. parser = argparse.ArgumentParser()
  61. parser.add_argument('--info_dir', type=str, default='./materials/name.txt')
  62. parser.add_argument('--save_dir', type=str, default='./imgs')
  63. args = parser.parse_args()
  64. generate_idcard(args.info_dir, args.save_dir)
  65. # image_cut_save('./idcard_0_02.png', 445, 340, 540, 370, 'result.png')