play.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import cv2
  2. import numpy as np
  3. from calculator import region_ndti, colorful_ndti_matrix
  4. def main(video_path, video_mask_path, video_id):
  5. records = []
  6. cap = cv2.VideoCapture(video_path)
  7. if not cap.isOpened():
  8. print("错误:无法打开视频文件。")
  9. print("可能的原因:文件路径错误,或系统缺少必要的解码器。")
  10. exit()
  11. scale = 4
  12. mask = cv2.imread(video_mask_path, cv2.IMREAD_GRAYSCALE)
  13. if mask is None:
  14. raise RuntimeError('mask open failed')
  15. mask = cv2.resize(mask, (mask.shape[1] // scale, mask.shape[0] // scale))
  16. fps = cap.get(cv2.CAP_PROP_FPS)
  17. print("fps:", fps)
  18. while True:
  19. ret, frame = cap.read() # ret指示是否成功读取帧,frame是图像数据
  20. if not ret:
  21. print("视频播放完毕。")
  22. break
  23. # 判断是否为夜间模式
  24. if np.mean(np.abs(frame[:, :, 0] - frame[:, :, 1])) < 0.1:
  25. is_night = True
  26. else:
  27. is_night = False
  28. frame = cv2.resize(frame, (frame.shape[1] // scale, frame.shape[0] // scale))
  29. # 计算掩膜区域的NDTI值
  30. roi_ndti = region_ndti(frame, mask, is_night)
  31. # 给ndti着色
  32. color_ndti = colorful_ndti_matrix(roi_ndti)
  33. # 仅保留感兴趣区的计算结果
  34. roi_index = mask > 0
  35. roi_ndti_fla = roi_ndti[roi_index]
  36. # 3σ原则
  37. # mean_value = np.mean(roi_ndti_fla)
  38. # std_value = np.std(roi_ndti_fla)
  39. # up_limit = mean_value + 3 * std_value
  40. # down_limit = mean_value - 3 * std_value
  41. # roi_ndti_fla = roi_ndti_fla[(up_limit >= roi_ndti_fla) & (roi_ndti_fla >= down_limit)]
  42. text = f'pixs:{int(np.sum(roi_ndti_fla))} mean:{roi_ndti_fla.mean():.3f} std:{roi_ndti_fla.std():.3f} {'night' if is_night else 'day'}'
  43. cv2.putText(frame, text, (10, 25), cv2.FONT_HERSHEY_DUPLEX, 0.6, (0, 255, 0), 2, cv2.LINE_AA)
  44. cv2.imshow(f'original_{video_id}', frame)
  45. cv2.waitKey(30)
  46. # 退出逻辑
  47. key = cv2.waitKey(10) & 0xFF
  48. if key == ord('q'):
  49. break
  50. if __name__ == '__main__':
  51. main(video_path=r'D:\code\water_turbidity_det\data\day_202511211129\1_video_202511211128.dav',
  52. video_mask_path=r'D:\code\water_turbidity_det\draw_mask\mask\1_device_capture.png',
  53. video_id=1)
  54. cv2.destroyAllWindows()