predict2.py 7.0 KB

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