基于Yolov7的路面病害检测代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.5KB

  1. """PyTorch Hub models
  2. Usage:
  3. import torch
  4. model = torch.hub.load('repo', 'model')
  5. """
  6. from pathlib import Path
  7. import torch
  8. from models.yolo import Model
  9. from utils.general import check_requirements, set_logging
  10. from utils.google_utils import attempt_download
  11. from utils.torch_utils import select_device
  12. dependencies = ['torch', 'yaml']
  13. check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
  14. set_logging()
  15. def create(name, pretrained, channels, classes, autoshape):
  16. """Creates a specified model
  17. Arguments:
  18. name (str): name of model, i.e. 'yolov7'
  19. pretrained (bool): load pretrained weights into the model
  20. channels (int): number of input channels
  21. classes (int): number of model classes
  22. Returns:
  23. pytorch model
  24. """
  25. try:
  26. cfg = list((Path(__file__).parent / 'cfg').rglob(f'{name}.yaml'))[0] # model.yaml path
  27. model = Model(cfg, channels, classes)
  28. if pretrained:
  29. fname = f'{name}.pt' # checkpoint filename
  30. attempt_download(fname) # download if not found locally
  31. ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
  32. msd = model.state_dict() # model state_dict
  33. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  34. csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
  35. model.load_state_dict(csd, strict=False) # load
  36. if len(ckpt['model'].names) == classes:
  37. model.names = ckpt['model'].names # set class names attribute
  38. if autoshape:
  39. model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  40. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  41. return model.to(device)
  42. except Exception as e:
  43. s = 'Cache maybe be out of date, try force_reload=True.'
  44. raise Exception(s) from e
  45. def custom(path_or_model='path/to/model.pt', autoshape=True):
  46. """custom mode
  47. Arguments (3 options):
  48. path_or_model (str): 'path/to/model.pt'
  49. path_or_model (dict): torch.load('path/to/model.pt')
  50. path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
  51. Returns:
  52. pytorch model
  53. """
  54. model = torch.load(path_or_model, map_location=torch.device('cpu')) if isinstance(path_or_model, str) else path_or_model # load checkpoint
  55. if isinstance(model, dict):
  56. model = model['ema' if model.get('ema') else 'model'] # load model
  57. hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
  58. hub_model.load_state_dict(model.float().state_dict()) # load state_dict
  59. hub_model.names = model.names # class names
  60. if autoshape:
  61. hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  62. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  63. return hub_model.to(device)
  64. def yolov7(pretrained=True, channels=3, classes=80, autoshape=True):
  65. return create('yolov7', pretrained, channels, classes, autoshape)
  66. if __name__ == '__main__':
  67. model = custom(path_or_model='yolov7.pt') # custom example
  68. # model = create(name='yolov7', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
  69. # Verify inference
  70. import numpy as np
  71. from PIL import Image
  72. imgs = [np.zeros((640, 480, 3))]
  73. results = model(imgs) # batched inference
  74. results.print()
  75. results.save()