main.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import os
  2. import sys
  3. import cv2
  4. import copy
  5. import torch
  6. import argparse
  7. root_path=os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 项目根路径:获取当前路径,再上级路径
  8. sys.path.append(root_path) # 将项目根路径写入系统路径
  9. from utils.general import check_img_size,non_max_suppression_face,scale_coords,xyxy2xywh
  10. from utils.datasets import letterbox
  11. from detect_plate import scale_coords_landmarks,show_results
  12. from torch2trt.trt_model import TrtModel
  13. cur_path=os.path.abspath(os.path.dirname(__file__))
  14. def img_process(img_path,long_side=640,stride_max=32):
  15. '''
  16. 图像预处理
  17. '''
  18. orgimg=cv2.imread(img_path)
  19. img0 = copy.deepcopy(orgimg)
  20. h0, w0 = orgimg.shape[:2] # orig hw
  21. r = long_side/ max(h0, w0) # resize image to img_size
  22. if r != 1: # always resize down, only resize up if training with augmentation
  23. interp = cv2.INTER_AREA if r < 1 else cv2.INTER_LINEAR
  24. img0 = cv2.resize(img0, (int(w0 * r), int(h0 * r)), interpolation=interp)
  25. imgsz = check_img_size(long_side, s=stride_max) # check img_size
  26. img = letterbox(img0, new_shape=imgsz,auto=False)[0] # auto True最小矩形 False固定尺度
  27. # Convert
  28. img = img[:, :, ::-1].transpose(2, 0, 1).copy() # BGR to RGB, to 3x416x416
  29. img = torch.from_numpy(img)
  30. img = img.float() # uint8 to fp16/32
  31. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  32. if img.ndimension() == 3:
  33. img = img.unsqueeze(0)
  34. return img,orgimg
  35. def img_vis(img,orgimg,pred,vis_thres = 0.6):
  36. '''
  37. 预测可视化
  38. vis_thres: 可视化阈值
  39. '''
  40. print('img.shape: ', img.shape)
  41. print('orgimg.shape: ', orgimg.shape)
  42. no_vis_nums=0
  43. # Process detections
  44. for i, det in enumerate(pred): # detections per image
  45. gn = torch.tensor(orgimg.shape)[[1, 0, 1, 0]] # normalization gain whwh
  46. gn_lks = torch.tensor(orgimg.shape)[[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]] # normalization gain landmarks
  47. if len(det):
  48. # Rescale boxes from img_size to im0 size
  49. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], orgimg.shape).round()
  50. # Print results
  51. for c in det[:, -1].unique():
  52. n = (det[:, -1] == c).sum() # detections per class
  53. det[:, 5:15] = scale_coords_landmarks(img.shape[2:], det[:, 5:15], orgimg.shape).round()
  54. for j in range(det.size()[0]):
  55. if det[j, 4].cpu().numpy() < vis_thres:
  56. no_vis_nums+=1
  57. continue
  58. xywh = (xyxy2xywh(det[j, :4].view(1, 4)) / gn).view(-1).tolist()
  59. conf = det[j, 4].cpu().numpy()
  60. landmarks = (det[j, 5:15].view(1, 10) / gn_lks).view(-1).tolist()
  61. class_num = det[j, 15].cpu().numpy()
  62. orgimg = show_results(orgimg, xywh, conf, landmarks, class_num)
  63. cv2.imwrite(cur_path+'/result.jpg', orgimg)
  64. print('result save in '+cur_path+'/result.jpg')
  65. if __name__ == '__main__':
  66. parser = argparse.ArgumentParser()
  67. parser.add_argument('--img_path', type=str, default=cur_path+"/sample.jpg", help='img path')
  68. parser.add_argument('--trt_path', type=str, required=True, help='trt_path')
  69. parser.add_argument('--output_shape', type=list, default=[1,25200,16], help='input[1,3,640,640] -> output[1,25200,16]')
  70. opt = parser.parse_args()
  71. img,orgimg=img_process(opt.img_path)
  72. model=TrtModel(opt.trt_path)
  73. pred=model(img.numpy()).reshape(opt.output_shape) # forward
  74. model.destroy()
  75. # Apply NMS
  76. pred = non_max_suppression_face(torch.from_numpy(pred), conf_thres=0.3, iou_thres=0.5)
  77. # ============可视化================
  78. img_vis(img,orgimg,pred)