video_test.py 12 KB

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