test.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import time
  2. import torch
  3. import torch.nn as nn
  4. from torchvision import transforms
  5. from torchvision.models import resnet18,resnet50, squeezenet1_0, shufflenet_v2_x1_0
  6. import numpy as np
  7. from PIL import Image
  8. import os
  9. import argparse
  10. from labelme.utils import draw_grid, draw_predict_grid
  11. import cv2
  12. import matplotlib.pyplot as plt
  13. from dotenv import load_dotenv
  14. load_dotenv()
  15. # os.environ['CUDA_LAUNCH_BLOCKING'] = '0'
  16. patch_w = int(os.getenv('PATCH_WIDTH', 256))
  17. patch_h = int(os.getenv('PATCH_HEIGHT', 256))
  18. confidence_threshold = float(os.getenv('CONFIDENCE_THRESHOLD', 0.80))
  19. scale = 2
  20. class Predictor:
  21. def __init__(self, model_name, weights_path, num_classes):
  22. self.model_name = model_name
  23. self.weights_path = weights_path
  24. self.num_classes = num_classes
  25. self.model = None
  26. self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  27. print(f"当前设备: {self.device}")
  28. # 加载模型
  29. self.load_model()
  30. def load_model(self):
  31. if self.model is not None:
  32. return
  33. print(f"正在加载模型: {self.model_name}")
  34. name = self.model_name
  35. # 加载模型
  36. if name == 'resnet50':
  37. self.model = resnet50()
  38. elif name == 'squeezenet':
  39. self.model = squeezenet1_0()
  40. elif name == 'shufflenet':
  41. self.model = shufflenet_v2_x1_0()
  42. else:
  43. raise ValueError(f"Invalid model name: {name}")
  44. # 替换最后的分类层以适应新的分类任务
  45. if hasattr(self.model, 'fc'):
  46. # ResNet系列模型
  47. self.model.fc = nn.Linear(int(self.model.fc.in_features), self.num_classes, bias=False)
  48. elif hasattr(self.model, 'classifier'):
  49. # Swin Transformer等模型
  50. self.model.classifier = nn.Linear(int(self.model.classifier.in_features), self.num_classes, bias=False)
  51. elif hasattr(self.model, 'head'):
  52. # Swin Transformer使用head层
  53. self.model.head = nn.Linear(int(self.model.head.in_features), self.num_classes, bias=False)
  54. else:
  55. raise ValueError(f"Model {name} does not have recognizable classifier layer")
  56. print(self.model)
  57. # 加载训练好的权重
  58. self.model.load_state_dict(torch.load(self.weights_path, map_location=torch.device('cpu')))
  59. print(f"成功加载模型参数: {self.weights_path}")
  60. # 将模型移动到GPU
  61. self.model.eval()
  62. self.model = self.model.to(self.device)
  63. print(f"成功加载模型: {self.model_name}")
  64. def predict(self, image_tensor):
  65. """
  66. 对单张图像进行预测
  67. Args:
  68. image_tensor: 预处理后的图像张量
  69. Returns:
  70. predicted_class: 预测的类别索引
  71. confidence: 预测置信度
  72. probabilities: 各类别的概率
  73. """
  74. image_tensor = image_tensor.to(self.device)
  75. with torch.no_grad():
  76. outputs = self.model(image_tensor)
  77. probabilities = torch.softmax(outputs, dim=1) # 沿行计算softmax
  78. confidence, predicted_class = torch.max(probabilities, 1)
  79. return confidence.cpu().numpy(), predicted_class.cpu().numpy()
  80. def preprocess_image(img):
  81. """
  82. 预处理图像以匹配训练时的预处理
  83. Args:
  84. img: PIL图像
  85. Returns:
  86. tensor: 预处理后的图像张量
  87. """
  88. # 定义与训练时相同的预处理步骤
  89. transform = transforms.Compose([
  90. transforms.Resize((224, 224)),
  91. transforms.ToTensor(),
  92. transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  93. ])
  94. # 打开并转换图像
  95. img_w, img_h = img.size
  96. global patch_w, patch_h
  97. imgs_patch = []
  98. imgs_index = []
  99. # fig, axs = plt.subplots(img_h // patch_h + 1, img_w // patch_w + 1)
  100. for i in range(img_h // patch_h + 1):
  101. for j in range(img_w // patch_w + 1):
  102. left = j * patch_w # 裁剪区域左边框距离图像左边的像素值
  103. top = i * patch_h # 裁剪区域上边框距离图像上边的像素值
  104. right = min(j * patch_w + patch_w, img_w) # 裁剪区域右边框距离图像左边的像素值
  105. bottom = min(i * patch_h + patch_h, img_h) # 裁剪区域下边框距离图像上边的像素值
  106. # 检查区域是否有效
  107. if right > left and bottom > top:
  108. patch = img.crop((left, top, right, bottom))
  109. # 长宽比过滤
  110. # rate = patch.height / (patch.width + 1e-6)
  111. # if rate > 1.314 or rate < 0.75:
  112. # # print(f"长宽比过滤: {patch_name}")
  113. # continue
  114. imgs_patch.append(patch)
  115. imgs_index.append((left, top))
  116. # axs[i, j].imshow(patch)
  117. # axs[i, j].set_title(f'Image {i} {j}')
  118. # axs[i, j].axis('off')
  119. # plt.tight_layout()
  120. # plt.show()
  121. imgs_patch = torch.stack([transform(img) for img in imgs_patch])
  122. # 添加批次维度
  123. # image_tensor = image_tensor.unsqueeze(0)
  124. return imgs_index, imgs_patch
  125. def visualize_prediction(image_path, predicted_class, confidence, class_names):
  126. """
  127. 可视化预测结果
  128. Args:
  129. image_path: 图像路径
  130. predicted_class: 预测的类别索引
  131. confidence: 预测置信度
  132. class_names: 类别名称列表
  133. """
  134. image = Image.open(image_path).convert('RGB')
  135. plt.figure(figsize=(8, 6))
  136. plt.imshow(image)
  137. plt.axis('off')
  138. plt.title(f'Predicted: {class_names[predicted_class]}\n'
  139. f'Confidence: {confidence:.4f}', fontsize=14)
  140. plt.show()
  141. def get_33_patch(arr:np.ndarray, center_row:int, center_col:int):
  142. """以(center_row,center_col)为中心,从arr中取出来3*3区域的数据"""
  143. # 边界检查
  144. h,w = arr.shape
  145. safe_row_up_limit = max(0, center_row-1)
  146. safe_row_bottom_limit = min(h, center_row+2)
  147. safe_col_left_limit = max(0, center_col-1)
  148. safe_col_right_limit = min(w, center_col+2)
  149. return arr[safe_row_up_limit:safe_row_bottom_limit, safe_col_left_limit:safe_col_right_limit]
  150. def fileter_prediction(predicted_class, confidence, pre_rows, pre_cols, filter_down_limit=3):
  151. """预测结果矩阵滤波,九宫格内部存在浑浊水体的数量需要大于filter_down_limit,"""
  152. predicted_class_mat = np.resize(predicted_class, (pre_rows, pre_cols))
  153. predicted_conf_mat = np.resize(confidence, (pre_rows, pre_cols))
  154. new_predicted_class_mat = predicted_class_mat.copy()
  155. new_predicted_conf_mat = predicted_conf_mat.copy()
  156. for i in range(pre_rows):
  157. for j in range(pre_cols):
  158. if (1. - predicted_class_mat[i, j]) > 0.1:
  159. continue # 跳过背景类
  160. core_region = get_33_patch(predicted_class_mat, i, j)
  161. if np.sum(core_region) < filter_down_limit:
  162. new_predicted_class_mat[i, j] = 0 # 重置为背景类
  163. new_predicted_conf_mat[i, j] = 1.0
  164. return new_predicted_conf_mat.flatten(), new_predicted_class_mat.flatten()
  165. def discriminate_ratio(water_pre_list:list):
  166. # 方式一:60%以上的帧存在浑浊水体
  167. water_pre_arr = np.array(water_pre_list, dtype=np.float32)
  168. water_pre_arr_mean = np.mean(water_pre_arr, axis=0)
  169. bad_water = np.array(water_pre_arr_mean >= 0.6, dtype=np.int32)
  170. bad_flag = np.sum(bad_water, dtype=np.int32)
  171. print(f'浑浊比例方式:该时间段是否存在浑浊水体:{bool(bad_flag)}')
  172. return bad_flag
  173. def discriminate_cont(pre_class_arr, continuous_count_mat):
  174. """连续帧判别"""
  175. positive_index = np.array(pre_class_arr,dtype=np.int32) > 0
  176. negative_index = np.array(pre_class_arr,dtype=np.int32) == 0
  177. # 给负样本区域置零
  178. continuous_count_mat[negative_index] = 0
  179. # 给正样本区域加1
  180. continuous_count_mat[positive_index] += 1
  181. # 判断浑浊
  182. bad_flag = np.max(continuous_count_mat) > 30
  183. if bad_flag:
  184. print(f'连续帧方式:该时间段是否存在浑浊水体:{bool(bad_flag)}')
  185. return bad_flag
  186. def main():
  187. # 初始化模型实例
  188. # TODO:修改模型网络名称/模型权重路径/视频路径
  189. predictor = Predictor(model_name='shufflenet',
  190. weights_path=r'/shufflenet.pth',
  191. num_classes=2)
  192. input_path = r'frame_data/train/20251225/4_video_202511211127'
  193. # 预处理图像
  194. all_imgs = os.listdir(input_path)
  195. all_imgs = [os.path.join(input_path, p) for p in all_imgs if p.split('.')[-1] in ['jpg', 'png']]
  196. image = Image.open(all_imgs[0]).convert('RGB')
  197. # 将预测结果reshape为矩阵时的行列数量
  198. pre_rows = image.height // patch_h + 1
  199. pre_cols = image.width // patch_w + 1
  200. # 图像显示时resize的尺寸
  201. resized_img_h = image.height // 2
  202. resized_img_w = image.width // 2
  203. # 预测每张图像
  204. water_pre_list = []
  205. continuous_count_mat = np.zeros(pre_rows*pre_cols, dtype=np.int32)
  206. flag = False
  207. for img_path in all_imgs:
  208. image = Image.open(img_path).convert('RGB')
  209. # 预处理
  210. patches_index, image_tensor = preprocess_image(image)
  211. # 推理
  212. confidence, predicted_class = predictor.predict(image_tensor)
  213. # 第一层虚警抑制,置信度过滤,低于阈值将会被忽略
  214. for i in range(len(confidence)):
  215. if confidence[i] < confidence_threshold:
  216. confidence[i] = 1.0
  217. predicted_class[i] = 0
  218. # 第二层虚警抑制,空间滤波
  219. # 在此处添加过滤逻辑
  220. new_confidence, new_predicted_class = fileter_prediction(predicted_class, confidence, pre_rows, pre_cols, filter_down_limit=3)
  221. # 可视化预测结果
  222. image = cv2.imread(img_path)
  223. image = draw_grid(image, patch_w, patch_h)
  224. image = draw_predict_grid(image, patches_index, predicted_class, confidence)
  225. new_image = cv2.imread(img_path)
  226. new_image = draw_grid(new_image, patch_w, patch_h)
  227. new_image = draw_predict_grid(new_image, patches_index, new_predicted_class, new_confidence)
  228. image = cv2.resize(image, (resized_img_w, resized_img_h))
  229. new_img = cv2.resize(new_image, (resized_img_w, resized_img_h))
  230. cv2.imshow('image', image)
  231. cv2.imshow('image_filter', new_img)
  232. cv2.waitKey(20)
  233. # 方式1判别
  234. if len(water_pre_list) > 100:
  235. flag = discriminate_ratio(water_pre_list) and flag
  236. water_pre_list = []
  237. print('综合判别结果:', flag)
  238. water_pre_list.append(new_predicted_class)
  239. # 方式2判别
  240. flag = discriminate_cont(new_predicted_class, continuous_count_mat)
  241. if __name__ == "__main__":
  242. main()