mask2small_classification.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. for i in range(0, num_width):
  39. for j in range(0, num_length):
  40. im = image[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
  41. ma = mask[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
  42. agv = np.sum(ma)/(ma.shape[0]*ma.shape[1]*ma.shape[2])
  43. if agv < 25:
  44. fire_name = 'nosmoke' #'./data/images/fire (1747).png'
  45. nosmoke_dir = os.path.join(pic_target, fire_name)
  46. if not os.path.exists(nosmoke_dir): # 判断是否存在文件夹如果不存在则创建为文件夹
  47. os.makedirs(nosmoke_dir)
  48. result_path = os.path.join(nosmoke_dir, fire_name + '_' + os.path.splitext(name)[0] + '_{}_{}_image.jpg'.format(i + 1, j + 1))
  49. else:
  50. fire_name = 'smoke'
  51. smoke_dir = os.path.join(pic_target, fire_name)
  52. if not os.path.exists(smoke_dir): # 判断是否存在文件夹如果不存在则创建为文件夹
  53. os.makedirs(smoke_dir)
  54. result_path = os.path.join(smoke_dir, fire_name + '_' + os.path.splitext(name)[0] + '_{}_{}_image.jpg'.format(i + 1, j + 1))
  55. # result_path = pic_target + fire_name + '_'+os.path.splitext(name)[0] +'_{}_{}_mask.jpg'.format(i + 1, j + 1)
  56. # cv2.imwrite(result_path, ma)
  57. cv2.imwrite(result_path, im)
  58. if __name__ == '__main__':
  59. masks_dir_path = './data1/mask'
  60. images_dir_path = './data1/images'
  61. # masks_dir_path = './data/test/mask'
  62. # images_dir_path = './data/fire'
  63. images_list_path = os.listdir(images_dir_path)
  64. for image_path in images_list_path:
  65. cut_small_images(os.path.join(images_dir_path, image_path), os.path.join(masks_dir_path, os.path.splitext(image_path)[0]+'.jpg'))