Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

132 rindas
4.3KB

  1. import torch
  2. import sys,os
  3. sys.path.extend(['../AIlib/segutils'])
  4. from model_stages import BiSeNet_STDC
  5. from torchvision import transforms
  6. import cv2,glob
  7. import numpy as np
  8. from core.models.dinknet import DinkNet34
  9. import matplotlib.pyplot as plt
  10. import time
  11. class SegModel(object):
  12. def __init__(self, nclass=2,weights=None,modelsize=(640,360),device='cuda:0'):
  13. #self.args = args
  14. self.model = BiSeNet_STDC(backbone='STDCNet813', n_classes=nclass,
  15. use_boundary_2=False, use_boundary_4=False,
  16. use_boundary_8=True, use_boundary_16=False,
  17. use_conv_last=False)
  18. self.device = device
  19. self.model.load_state_dict(torch.load(weights, map_location=torch.device(self.device) ))
  20. self.model= self.model.to(self.device)
  21. self.mean = (0.485, 0.456, 0.406)
  22. self.std = (0.229, 0.224, 0.225)
  23. self.modelsize=modelsize
  24. def eval(self,image):
  25. time0 = time.time()
  26. imageH, imageW, _ = image.shape
  27. image = self.RB_convert(image)
  28. img = self.preprocess_image(image)
  29. if self.device != 'cpu':
  30. imgs = img.to(self.device)
  31. else:imgs=img
  32. time1 = time.time()
  33. self.model.eval()
  34. with torch.no_grad():
  35. output = self.model(imgs)
  36. time2 = time.time()
  37. pred = output.data.cpu().numpy()
  38. pred = np.argmax(pred, axis=1)[0]#得到每行
  39. time3 = time.time()
  40. pred = cv2.resize(pred.astype(np.uint8),(imageW,imageH))
  41. time4 = time.time()
  42. outstr= 'pre-precess:%.1f ,infer:%.1f ,post-cpu-argmax:%.1f ,post-resize:%.1f, total:%.1f \n '%( self.get_ms(time1,time0),self.get_ms(time2,time1),self.get_ms(time3,time2),self.get_ms(time4,time3),self.get_ms(time4,time0) )
  43. return pred,outstr
  44. def get_ms(self,t1,t0):
  45. return (t1-t0)*1000.0
  46. def preprocess_image(self,image):
  47. image = cv2.resize(image, self.modelsize, interpolation=cv2.INTER_LINEAR)
  48. image = image.astype(np.float32)
  49. image /= 255.0
  50. image[:, :, 0] -= self.mean[0]
  51. image[:, :, 1] -= self.mean[1]
  52. image[:, :, 2] -= self.mean[2]
  53. image[:, :, 0] /= self.std[0]
  54. image[:, :, 1] /= self.std[1]
  55. image[:, :, 2] /= self.std[2]
  56. image = np.transpose(image, (2, 0, 1))
  57. image = torch.from_numpy(image).float()
  58. image = image.unsqueeze(0)
  59. return image
  60. def RB_convert(self,image):
  61. image_c = image.copy()
  62. image_c[:,:,0] = image[:,:,2]
  63. image_c[:,:,2] = image[:,:,0]
  64. return image_c
  65. def get_ms(t1,t0):
  66. return (t1-t0)*1000.0
  67. def get_largest_contours(contours):
  68. areas = [cv2.contourArea(x) for x in contours]
  69. max_area = max(areas)
  70. max_id = areas.index(max_area)
  71. return max_id
  72. if __name__=='__main__':
  73. impth = '../../../../data/无人机起飞测试图像/'
  74. outpth= 'results'
  75. folders = os.listdir(impth)
  76. weights = '../weights/STDC/model_maxmIOU75_1720_0.946_360640.pth'
  77. segmodel = SegModel(nclass=2,weights=weights)
  78. for i in range(len(folders)):
  79. imgpath = os.path.join(impth, folders[i])
  80. time0 = time.time()
  81. #img = Image.open(imgpath).convert('RGB')
  82. img = cv2.imread(imgpath)
  83. img = np.array(img)
  84. time1 = time.time()
  85. pred, outstr = segmodel.eval(image=img)#####
  86. time2 = time.time()
  87. binary0 = pred.copy()
  88. contours, hierarchy = cv2.findContours(binary0,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  89. time3 = time.time()
  90. max_id = -1
  91. if len(contours)>0:
  92. max_id = get_largest_contours(contours)
  93. binary0[:,:] = 0
  94. cv2.fillPoly(binary0, [contours[max_id][:,0,:]], 1)
  95. cv2.drawContours(img,contours,max_id,(0,255,255),3)
  96. time4 = time.time()
  97. #img_n = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
  98. cv2.imwrite( os.path.join( outpth,folders[i] ) ,img )
  99. time5 = time.time()
  100. print('image:%d ,infer:%.1f ms,findcontours:%.1f ms, draw:%.1f, total:%.1f'%(i,get_ms(time2,time1),get_ms(time3,time2),get_ms(time4,time3),get_ms(time4,time1)))