utils.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import numpy as np
  2. from PIL import Image
  3. #---------------------------------------------------------#
  4. # 将图像转换成RGB图像,防止灰度图在预测时报错。
  5. # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
  6. #---------------------------------------------------------#
  7. def cvtColor(image):
  8. if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
  9. return image
  10. else:
  11. image = image.convert('RGB')
  12. return image
  13. #---------------------------------------------------#
  14. # 对输入图像进行resize
  15. #---------------------------------------------------#
  16. def resize_image(image, size):
  17. w, h = size
  18. new_image = image.resize((w, h), Image.BICUBIC)
  19. return new_image
  20. #---------------------------------------------------#
  21. # 获得类
  22. #---------------------------------------------------#
  23. def get_classes(classes_path):
  24. with open(classes_path, encoding='utf-8') as f:
  25. class_names = f.readlines()
  26. class_names = [c.strip() for c in class_names]
  27. return class_names, len(class_names)
  28. #---------------------------------------------------#
  29. # 获得学习率
  30. #---------------------------------------------------#
  31. def get_lr(optimizer):
  32. for param_group in optimizer.param_groups:
  33. return param_group['lr']
  34. def preprocess_input(image):
  35. image /= 255.0
  36. return image
  37. def show_config(**kwargs):
  38. print('Configurations:')
  39. print('-' * 70)
  40. print('|%25s | %40s|' % ('keys', 'values'))
  41. print('-' * 70)
  42. for key, value in kwargs.items():
  43. print('|%25s | %40s|' % (str(key), str(value)))
  44. print('-' * 70)
  45. def get_new_img_size(height, width, img_min_side=600):
  46. if width <= height:
  47. f = float(img_min_side) / width
  48. resized_height = int(f * height)
  49. resized_width = int(img_min_side)
  50. else:
  51. f = float(img_min_side) / height
  52. resized_width = int(f * width)
  53. resized_height = int(img_min_side)
  54. return resized_height, resized_width