mask2small_classification.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. # File : mask2small.py
  3. # Time :2024-04-23 16:40
  4. # Author :FEANGYANG
  5. # version :python 3.7
  6. # Contact :1071082183@qq.com
  7. # Description:
  8. """
  9. """
  10. # File : mask2iou.py
  11. # Time :2024-04-08 13:35
  12. # Author :FEANGYANG
  13. # version :python 3.7
  14. # Contact :1071082183@qq.com
  15. # Description:
  16. """
  17. import os
  18. import cv2
  19. import numpy as np
  20. def cut_small_images(image_path, mask_path, pic_target='./result_class/'):
  21. if not os.path.exists(pic_target): # 判断是否存在文件夹如果不存在则创建为文件夹
  22. os.makedirs(pic_target)
  23. image = cv2.imread(image_path)
  24. mask = cv2.imread(mask_path)
  25. name = os.path.split(image_path)[-1]
  26. (width, length, depth) = image.shape
  27. w, h, _ = image.shape
  28. # _w = w % pixes
  29. # _h = h % pixes
  30. cut_width = cut_length = 128
  31. # 预处理生成0矩阵
  32. pic = np.zeros((cut_width, cut_length, depth))
  33. # 计算可以划分的横纵的个数
  34. num_width = int(width / cut_width)
  35. num_length = int(length / cut_length)
  36. # for循环迭代生成
  37. lines_list = []
  38. print(image_path)
  39. for i in range(0, num_width):
  40. for j in range(0, num_length):
  41. im = image[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
  42. ma = mask[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
  43. agv = np.sum(ma)/(ma.shape[0]*ma.shape[1]*ma.shape[2])
  44. if agv < 25:
  45. fire_name = 'nosmoke' #'./data/images/fire (1747).png'
  46. nosmoke_dir = os.path.join(pic_target, fire_name)
  47. if not os.path.exists(nosmoke_dir): # 判断是否存在文件夹如果不存在则创建为文件夹
  48. os.makedirs(nosmoke_dir)
  49. result_path = os.path.join(nosmoke_dir, fire_name + '_' + os.path.splitext(name)[0] + '_{}_{}_image.jpg'.format(i + 1, j + 1))
  50. else:
  51. fire_name = 'smoke'
  52. smoke_dir = os.path.join(pic_target, fire_name)
  53. if not os.path.exists(smoke_dir): # 判断是否存在文件夹如果不存在则创建为文件夹
  54. os.makedirs(smoke_dir)
  55. result_path = os.path.join(smoke_dir, fire_name + '_' + os.path.splitext(name)[0] + '_{}_{}_image.jpg'.format(i + 1, j + 1))
  56. # result_path = pic_target + fire_name + '_'+os.path.splitext(name)[0] +'_{}_{}_mask.jpg'.format(i + 1, j + 1)
  57. # cv2.imwrite(result_path, ma)
  58. cv2.imwrite(result_path, im)
  59. if __name__ == '__main__':
  60. masks_dir_path = './data/mask'
  61. images_dir_path = './data/images'
  62. # masks_dir_path = './data/test/mask'
  63. # images_dir_path = './data/fire'
  64. images_list_path = os.listdir(images_dir_path)
  65. for image_path in images_list_path:
  66. cut_small_images(os.path.join(images_dir_path, image_path), os.path.join(masks_dir_path, os.path.splitext(image_path)[0]+'.jpg'))