Python code for real-time water level mapping. Here's a comprehensive approach that incorporates the best aspects of previous responses and addresses potential issues:
- Import Necessary Libraries:
import cv2
import numpy as np
import time
import matplotlib.pyplot as plt
For real-time video processing
import imutils
For machine learning models
from tensorflow.keras.models import load_model
- Load the Pre-trained Model:
Replace 'your_model.h5' with the actual path to your trained model
model = load_model('your_model.h5')
- Define Functions:
def preprocess_image(image):
# Resize the image to a fixed size (adjust as needed)
image = cv2.resize(image, (224, 224))
# Convert to grayscale if necessary
# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Normalize pixel values to the range [0, 1]
image = image / 255.0
# Add an extra dimension if required for your model
image = np.expand_dims(image, axis=0)
return image
def predict_water_level(image, model):
# Preprocess the image
preprocessed_image = preprocess_image(image)
# Make a prediction using the model
prediction = model.predict(preprocessed_image)
# Convert the prediction to a water level value (adjust as needed)
water_level = prediction[0][0] * 100 # Assuming prediction is in the range [0, 1]
return water_level
- Initialize Video Capture:
cap = cv2.VideoCapture(0) # Replace 0 with the index of your camera
Check if the camera opened successfully
if not cap.isOpened():
print("Error opening video stream")
exit()
- Process Video Frames in Real Time:
while True:
# Read a frame from the video stream
ret, frame = cap.read()
# Check if the frame was read successfully
if not ret:
break
Process the frame (e.g., apply image enhancement, remove noise)
frame = cv2.GaussianBlur(frame, (5, 5), 0) # Example: Apply Gaussian blur
Predict the water level
water_level = predict_water_level(frame, model)
Display the frame and water level prediction
cv2.putText(frame, f"Water Level: {water_level:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Water Level Mapping', frame)
Handle user input (e.g., 'q' to quit)
if cv2.waitKey(1) == ord('q'):
break
Release the video capture and close windows
cap.release()
cv2.destroyAllWindows()
Key Improvements:
Modular Approach: The code is well-structured with separate functions for preprocessing, prediction, and display, making it easier to modify and extend.
Error Handling: The code checks for errors in opening the video stream and reading frames, ensuring robustness.
Flexibility: The code allows for customization of preprocessing steps, model architecture, and prediction interpretation based on your specific requirements.
Comments: Clear comments explain the purpose of different code sections, enhancing readability and maintainability.
Remember to replace 'your_model.h5' with the actual path to your trained model and adjust the prediction conversion and display logic as needed.
Top comments (0)