predict2.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import time
  2. import skimage
  3. from models.line_detect.postprocess import show_predict, show_line, show_box, show_box_or_line, show_box_and_line
  4. import os
  5. import torch
  6. from PIL import Image
  7. import matplotlib.pyplot as plt
  8. import matplotlib as mpl
  9. import numpy as np
  10. from models.line_detect.line_net import linenet_resnet50_fpn
  11. from torchvision import transforms
  12. # from models.wirenet.postprocess import postprocess
  13. from models.wirenet.postprocess import postprocess
  14. from rtree import index
  15. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  16. def load_best_model(model, save_path, device):
  17. if os.path.exists(save_path):
  18. checkpoint = torch.load(save_path, map_location=device)
  19. model.load_state_dict(checkpoint['model_state_dict'])
  20. # if optimizer is not None:
  21. # optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
  22. epoch = checkpoint['epoch']
  23. loss = checkpoint['loss']
  24. print(f"Loaded best model from {save_path} at epoch {epoch} with loss {loss:.4f}")
  25. else:
  26. print(f"No saved model found at {save_path}")
  27. return model
  28. def box_line_(pred):
  29. for idx, box_ in enumerate(pred[0:-1]):
  30. box = box_['boxes'] # 是一个tensor
  31. line = pred[-1]['wires']['lines'][idx].cpu().numpy() / 128 * 512
  32. score = pred[-1]['wires']['score'][idx]
  33. line_ = []
  34. score_ = []
  35. for i in box:
  36. score_max = 0.0
  37. tmp = [[0.0, 0.0], [0.0, 0.0]]
  38. for j in range(len(line)):
  39. if (line[j][0][1] >= i[0] and line[j][1][1] >= i[0] and
  40. line[j][0][1] <= i[2] and line[j][1][1] <= i[2] and
  41. line[j][0][0] >= i[1] and line[j][1][0] >= i[1] and
  42. line[j][0][0] <= i[3] and line[j][1][0] <= i[3]):
  43. if score[j] > score_max:
  44. tmp = line[j]
  45. score_max = score[j]
  46. line_.append(tmp)
  47. score_.append(score_max)
  48. processed_list = torch.tensor(line_)
  49. pred[idx]['line'] = processed_list
  50. processed_s_list = torch.tensor(score_)
  51. pred[idx]['line_score'] = processed_s_list
  52. return pred
  53. def box_line_optimized(pred):
  54. # 创建R-tree索引
  55. idx = index.Index()
  56. # 将所有线段添加到R-tree中
  57. lines = pred[-1]['wires']['lines'] # 形状为[1, 2500, 2, 2]
  58. scores = pred[-1]['wires']['score'][0] # 假设形状为[2500]
  59. # 提取并处理所有线段
  60. for idx_line in range(lines.shape[1]): # 遍历2500条线段
  61. line_tensor = lines[0, idx_line].cpu().numpy() / 128 * 512 # 转换为numpy数组并调整比例
  62. x_min = float(min(line_tensor[0][0], line_tensor[1][0]))
  63. y_min = float(min(line_tensor[0][1], line_tensor[1][1]))
  64. x_max = float(max(line_tensor[0][0], line_tensor[1][0]))
  65. y_max = float(max(line_tensor[0][1], line_tensor[1][1]))
  66. idx.insert(idx_line, (max(0, x_min - 256), max(0, y_min - 256), min(512, x_max + 256), min(512, y_max + 256)))
  67. for idx_box, box_ in enumerate(pred[0:-1]):
  68. box = box_['boxes'].cpu().numpy() # 确保将张量转换为numpy数组
  69. line_ = []
  70. score_ = []
  71. for i in box:
  72. score_max = 0.0
  73. tmp = [[0.0, 0.0], [0.0, 0.0]]
  74. # 获取与当前box可能相交的所有线段
  75. possible_matches = list(idx.intersection((i[0], i[1], i[2], i[3])))
  76. for j in possible_matches:
  77. line_j = lines[0, j].cpu().numpy() / 128 * 512
  78. if (line_j[0][1] >= i[0] and line_j[1][1] >= i[0] and # 注意这里交换了x和y
  79. line_j[0][1] <= i[2] and line_j[1][1] <= i[2] and
  80. line_j[0][0] >= i[1] and line_j[1][0] >= i[1] and
  81. line_j[0][0] <= i[3] and line_j[1][0] <= i[3]):
  82. if scores[j] > score_max:
  83. tmp = line_j
  84. score_max = scores[j]
  85. line_.append(tmp)
  86. score_.append(score_max)
  87. processed_list = torch.tensor(line_)
  88. pred[idx_box]['line'] = processed_list
  89. processed_s_list = torch.tensor(score_)
  90. pred[idx_box]['line_score'] = processed_s_list
  91. return pred
  92. def predict(pt_path, model, img):
  93. model = load_best_model(model, pt_path, device)
  94. model.eval()
  95. if isinstance(img, str):
  96. img = Image.open(img).convert("RGB")
  97. transform = transforms.ToTensor()
  98. img_tensor = transform(img) # [3, 512, 512]
  99. # img_ = img_tensor
  100. # 将图像调整为512x512大小
  101. t_start = time.time()
  102. im = img_tensor.permute(1, 2, 0) # [512, 512, 3]
  103. im_resized = skimage.transform.resize(im.cpu().numpy().astype(np.float32), (512, 512)) # (512, 512, 3)
  104. img_ = torch.tensor(im_resized).permute(2, 0, 1)
  105. t_end = time.time()
  106. print(f'switch img used:{t_end - t_start}')
  107. with torch.no_grad():
  108. predictions = model([img_.to(device)])
  109. # print(predictions)
  110. show_line(img_, predictions, t_start) # 只画线
  111. # show_box(img_, predictions, t_start) # 只画kuang
  112. # show_box_or_line(img_, predictions, show_line=True, show_box=True) # 参数确定画什么
  113. # show_box_and_line(img_, predictions, show_line=True, show_box=True) # 一起画 1x2 2张图
  114. # t_start = time.time()
  115. # # pred = box_line_optimized(predictions)
  116. # pred = box_line_(predictions)
  117. # t_end = time.time()
  118. # print(f'Matched boxes and lines used: {t_end - t_start:.4f} seconds')
  119. # show_predict(img_, pred, t_start)
  120. if __name__ == '__main__':
  121. t_start = time.time()
  122. print(f'start to predict:{t_start}')
  123. model = linenet_resnet50_fpn().to(device)
  124. pt_path = r'D:\python\PycharmProjects\20250214\weight\resnet50_best_e100.pth'
  125. # img_path = f'D:\python\PycharmProjects\data2\images/train/2024-11-27-15-41-38_SaveImage.png' # 工件图
  126. # img_path = f'D:\python\PycharmProjects\data\images/train/00558656_3.png' # wireframe图
  127. img_path = r'C:\Users\m2337\Desktop\9.jpg'
  128. predict(pt_path, model, img_path)
  129. t_end = time.time()
  130. print(f'predict used:{t_end - t_start}')