corner_refiner.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import numpy as np
  2. from PIL import Image
  3. import paddle.inference as paddle_infer
  4. import paddle.vision.transforms as T
  5. class corner_finder():
  6. def __init__(self, model, params):
  7. config = paddle_infer.Config(model, params)
  8. self.predictor = paddle_infer.create_predictor(config)
  9. def get_location(self, img, retainFactor=0.85):
  10. trans = T.ToTensor()
  11. resi = T.Resize([32, 32])
  12. ans_x = 0.0
  13. ans_y = 0.0
  14. o_img = np.copy(img)
  15. y = [0, 0]
  16. x_start = 0
  17. y_start = 0
  18. up_scale_factor = (img.shape[1], img.shape[0])
  19. myImage = np.copy(o_img)
  20. CROP_FRAC = retainFactor
  21. while (myImage.shape[0] > 10 and myImage.shape[1] > 10):
  22. img_temp = Image.fromarray(myImage)
  23. img_temp = trans(img_temp)
  24. img_temp = resi(img_temp)
  25. img_temp = np.expand_dims(img_temp, 0)
  26. input_names = self.predictor.get_input_names()
  27. input_handle = self.predictor.get_input_handle(input_names[0])
  28. input_handle.reshape([1, 3, 32, 32])
  29. input_handle.copy_from_cpu(img_temp)
  30. # 运行predictor
  31. self.predictor.run()
  32. # 获取输出
  33. output_names = self.predictor.get_output_names()
  34. output_handle = self.predictor.get_output_handle(output_names[0])
  35. output_data = output_handle.copy_to_cpu() # numpy.ndarray类型
  36. output_data = output_data[0]
  37. model_prediction = np.array(output_data)
  38. response_up = model_prediction
  39. response_up = response_up * up_scale_factor
  40. y = response_up + (x_start, y_start)
  41. x_loc = int(y[0])
  42. y_loc = int(y[1])
  43. if x_loc > myImage.shape[1] / 2:
  44. start_x = min(x_loc + int(round(myImage.shape[1] * CROP_FRAC / 2)), myImage.shape[1]) - int(round(
  45. myImage.shape[1] * CROP_FRAC))
  46. else:
  47. start_x = max(x_loc - int(myImage.shape[1] * CROP_FRAC / 2), 0)
  48. if y_loc > myImage.shape[0] / 2:
  49. start_y = min(y_loc + int(myImage.shape[0] * CROP_FRAC / 2), myImage.shape[0]) - int(
  50. myImage.shape[0] * CROP_FRAC)
  51. else:
  52. start_y = max(y_loc - int(myImage.shape[0] * CROP_FRAC / 2), 0)
  53. ans_x += start_x
  54. ans_y += start_y
  55. myImage = myImage[start_y:start_y + int(myImage.shape[0] * CROP_FRAC),
  56. start_x:start_x + int(myImage.shape[1] * CROP_FRAC)]
  57. img = img[start_y:start_y + int(img.shape[0] * CROP_FRAC),
  58. start_x:start_x + int(img.shape[1] * CROP_FRAC)]
  59. up_scale_factor = (img.shape[1], img.shape[0])
  60. ans_x += y[0]
  61. ans_y += y[1]
  62. return (int(round(ans_x)), int(round(ans_y)))
  63. if __name__ == "__main__":
  64. pass