plate_rec.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. from plate_recognition.plateNet import myNet_ocr_color
  2. import torch
  3. import cv2
  4. import numpy as np
  5. import os
  6. import time
  7. def cv_imread(path): # 可以读取中文路径的图片
  8. img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)
  9. return img
  10. def allFilePath(rootPath, allFIleList):
  11. fileList = os.listdir(rootPath)
  12. for temp in fileList:
  13. if os.path.isfile(os.path.join(rootPath, temp)):
  14. if temp.endswith(".jpg") or temp.endswith(".png") or temp.endswith(".JPG"):
  15. allFIleList.append(os.path.join(rootPath, temp))
  16. else:
  17. allFilePath(os.path.join(rootPath, temp), allFIleList)
  18. device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
  19. color = ["黑色", "蓝色", "绿色", "白色", "黄色"]
  20. plateName = r"#京沪津渝冀晋蒙辽吉黑苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新学警港澳挂使领民航危0123456789ABCDEFGHJKLMNPQRSTUVWXYZ险品"
  21. mean_value, std_value = (0.588, 0.193)
  22. def decodePlate(preds):
  23. pre = 0
  24. newPreds = []
  25. index = []
  26. for i in range(len(preds)):
  27. if preds[i] != 0 and preds[i] != pre:
  28. newPreds.append(preds[i])
  29. index.append(i)
  30. pre = preds[i]
  31. return newPreds, index
  32. def image_processing(img, device):
  33. img = cv2.resize(img, (168, 48))
  34. img = np.reshape(img, (48, 168, 3))
  35. # normalize
  36. img = img.astype(np.float32)
  37. img = (img / 255.0 - mean_value) / std_value
  38. img = img.transpose([2, 0, 1])
  39. img = torch.from_numpy(img)
  40. img = img.to(device)
  41. img = img.view(1, *img.size())
  42. return img
  43. def get_plate_result(img, device, model, is_color=False):
  44. input = image_processing(img, device)
  45. if is_color: # 是否识别颜色
  46. preds, color_preds = model(input)
  47. color_preds = torch.softmax(color_preds, dim=-1)
  48. color_conf, color_index = torch.max(color_preds, dim=-1)
  49. color_conf = color_conf.item()
  50. else:
  51. preds = model(input)
  52. preds = torch.softmax(preds, dim=-1)
  53. prob, index = preds.max(dim=-1)
  54. index = index.view(-1).detach().cpu().numpy()
  55. prob = prob.view(-1).detach().cpu().numpy()
  56. # preds=preds.view(-1).detach().cpu().numpy()
  57. newPreds, new_index = decodePlate(index)
  58. prob = prob[new_index]
  59. plate = ""
  60. for i in newPreds:
  61. plate += plateName[i]
  62. # if not (plate[0] in plateName[1:44] ):
  63. # return ""
  64. if is_color:
  65. return (
  66. plate,
  67. prob,
  68. color[color_index],
  69. color_conf,
  70. ) # 返回车牌号以及每个字符的概率,以及颜色,和颜色的概率
  71. else:
  72. return plate, prob
  73. def init_model(device, model_path, is_color=False):
  74. # print( print(sys.path))
  75. # model_path ="plate_recognition/model/checkpoint_61_acc_0.9715.pth"
  76. check_point = torch.load(model_path, map_location=device)
  77. model_state = check_point["state_dict"]
  78. cfg = check_point["cfg"]
  79. color_classes = 0
  80. if is_color:
  81. color_classes = 5 # 颜色类别数
  82. model = myNet_ocr_color(
  83. num_classes=len(plateName), export=True, cfg=cfg, color_num=color_classes
  84. )
  85. model.load_state_dict(model_state, strict=False)
  86. model.to(device)
  87. model.eval()
  88. return model
  89. # model = init_model(device)
  90. if __name__ == "__main__":
  91. model_path = r"weights/plate_rec_color.pth"
  92. image_path = "images/tmp2424.png"
  93. testPath = r"/mnt/Gpan/Mydata/pytorchPorject/CRNN/crnn_plate_recognition/images"
  94. fileList = []
  95. allFilePath(testPath, fileList)
  96. # result = get_plate_result(image_path,device)
  97. # print(result)
  98. is_color = True
  99. model = init_model(device, model_path, is_color=is_color)
  100. right = 0
  101. begin = time.time()
  102. for imge_path in fileList:
  103. img = cv2.imread(imge_path)
  104. if is_color:
  105. plate, _, plate_color, _ = get_plate_result(
  106. img, device, model, is_color=is_color
  107. )
  108. print(plate)
  109. else:
  110. plate, _ = get_plate_result(img, device, model, is_color=is_color)
  111. print(plate, imge_path)