should we put our collection uuid in firestore for this one? since our uuid firestore database is Detections for every people detected on our computer vision so that the web app will display the number of people detected and store to our firestore firebsase
Assistant
User
Assistant
It seems you are asking about integrating your computer vision detections, which presumably involve storing and updating a UUID for each detected person to Firebase Firestore, to dynamically display the count of detected people on your web app.
To achieve this, you would architect a system where:
Your computer vision service pushes detection events (with UUIDs) to Firestore.
Firestore serves as your source of truth for the current detection state.
Your web app listens for updates from Firestore and updates the UI accordingly.
Here's an outline of how to implement this:
Computer Vision Integration:
Assign a UUID for each person detected.
On each event (detection), push this data to a Firestore collection named Detections.
Firestore Collection:
Create a Firestore collection called Detections.
For each detection, add a document with fields like uuid, detectedAt, and any other pertinent info.
Web App Modifications:
Import Firebase into your web app if not already done. (Refer to Firebase documentation on how to add Firebase to your web project: https://firebase.google.com/docs/web/setup)
Use Firestore's real-time database feature to listen for changes to the Detections collection.
Example Firestore listener snippet in a Svelte script:
javascript
<script>
import { onSnapshot, collection } from 'firebase/firestore';
import { db } from './yourFirebaseConfig'; // Ensure you import your Firebase configuration
let peopleDetected = 0;
const unsubscribe = onSnapshot(collection(db, 'Detections'), (snapshot) => {
// Every time something changes in the 'Detections' collection, this function is called with the current snapshot
peopleDetected = snapshot.size; // Number of documents in the 'Detections' collection
// Perform necessary steps to update people counts or any other variables
});
// Don't forget to unsubscribe when your component is destroyed to prevent memory leaks
onDestroy(() => {
unsubscribe();
});
</script>
Displaying the Count in the Component:
Replace the lines that calculate down and up with the real-time data from Firestore.
Update your UI to reflect the dynamic count.
Now, your web application should display a real-time count of people detected by your computer vision system, as reported to Firestore.
Finally, ensure you have appropriate security rules set up in Firestore to protect your data, allowing only authorized access.
Remember, handling Firebase configuration and security is critical, so follow best practices as outlined in Firebase documentation. If needed, consult with a Firebase expert or an experienced web developer to integrate Firestore's real-time capabilities securely into your application.
this is my code for home page for our web app is svelte :
this is our gettotalnumberofpeople.js database
import { collection, getDocs, onSnapshot } from "firebase/firestore";
import db from "../auth/firestore"
import { writable } from "svelte/store";
// Set up a realtime listener to update the reactive store whenever there is new data
onSnapshot(collection(db, "Total"), (snapshot) => {
if(snapshot){
snapshot.docChanges().forEach((change) => {
if (change.type === "added" || change.type === "removed") {
getTotalNumberOfPeople().then((out) => {
people.set(out);
});
}
});
setPeople()
}
}, (error) => {
console.error(error);
});
Define the ROI polygon points (clockwise or counter-clockwise)
roi_polygon = np.array([
[150, 150], # Point 1 (x1, y1)
[1050, 150], # Point 2 (x2, y2)
[1050, 650], # Point 3 (x3, y3)
[150, 650] # Point 4 (x4, y4)
], dtype=np.int32)
def create_mask(frame, roi_polygon):
# Create a black mask with the same dimensions as the frame
mask = np.zeros_like(frame, dtype=np.uint8)
code
# Fill the ROI polygon with white color
cv2.fillPoly(mask, [roi_polygon], (255, 255, 255))
# Mask the frame to only keep ROI and set everything else to black
frame_roi = cv2.bitwise_and(frame, mask)
return frame_roi
def live_inference(camera):
while True:
# Capture frame-by-frame from camera
ret, frame = camera.read()
if not ret:
print("Failed to grab frame")
break
code
# Convert the image from BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Apply the ROI mask to the frame
frame_roi = create_mask(frame_rgb, roi_polygon)
# Perform inference on the masked frame
results = model(frame_roi)
detections = sv.Detections.from_yolov5(results)
# Set threshold and class filtering as before
detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)]
# Annotate detections on the original frame (not the masked one)
frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections)
# Draw the ROI polygon on the annotated frame
cv2.polylines(frame_annotated, [roi_polygon], isClosed=True, color=(0, 255, 0), thickness=3)
# Get the number of detections within the ROI
num_detections = len(detections)
# Display the number of detected objects on the frame
text = f"Detections in ROI: {num_detections}"
cv2.putText(frame_annotated, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
# Convert the image from RGB to BGR for OpenCV display
frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR)
# Display the resulting frame
cv2.imshow('OLOv5 Live Detection', frame_annotated_bgr)
# Send the total number of detections to Firestore
# Get the current UTC date and time
utc_datetime = datetime.datetime.now(tz=pytz.UTC)
# Convert the UTC date and time to your local timezone, e.g., GMT+8
local_timezone = pytz.timezone('Asia/Singapore') # Replace 'Your/Timezone' with your timezone
local_datetime = utc_datetime.astimezone(local_timezone)
# Generate a unique string identifier for the Firestore document
uuid_val = str(uuid.uuid4())
# Create a new document in the Firestore collection
doc_ref = db.collection(u'Detections').document(uuid_val)
doc_ref.set({
u'DateTime': local_datetime,
u'Count': num_detections
})
# Break the loop if ‘q’ is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
camera.release()
cv2.destroyAllWindows()
Run the live inference function
live_inference(camera)
all of these are connected to our firestore firebase. when a person is detected in our CV in updates the Detections collection in our firebase. however its not showing in our svelte web app.
this is also the part where after "Current People:" is the number of currently detected people on our CV. how do i update this? {down - up < 0 ? 0 : down - up} to show the number of people detected.
analyze the code thoroughly
It looks like you have several different systems in play here:
Your getTotalNumberOfPeople.js aims to retrieve and listen for changes in detections from Firestore (in a collection called "Total" which is a bit confusing since it seems like actual detections are stored in a "Detections" collection as per your CV code).
Your computer vision (CV) Python script is sending detection counts to the Firestore collection named "Detections".
Your Svelte web app seems to want to display the number of people currently detected, but the logic isn't connecting to your Firestore data correctly.
Let's address these issues step by step.
First, your computer vision script is pushing every detection count with a new UUID. Each record is a separate document. You may need a different structure which maintains current state, rather than historical state. Alternatively, you'll need to pull and sum all counts from all the documents to represent the current detected number.
Second, for your web app, you'll want to listen to the correct Firestore collection that your CV script updates ('Detections', as in your Python script). Right now, you have $people which seems to point to a "Total" collection.
Here's an adjusted version of getTotalNumberOfPeople.js which listens to the 'Detections' collection:
javascript
import { onSnapshot, collection } from "firebase/firestore";
import db from "../auth/firestore"
import { writable } from "svelte/store";
export let detections = writable([]);
function updateDetections(snapshot) {
let newDetections = [];
snapshot.forEach(doc => {
let data = doc.data();
if(data.Count !== undefined) {
newDetections.push(data);
}
});
detections.set(newDetections);
}
// Set up a realtime listener to update the reactive store whenever there is new data
onSnapshot(collection(db, "Detections"), updateDetections, (error) => {
console.error(error);
});
export default detections;
In your web app, you would then:
Import the adapted store that listens for changes to the 'Detections' collection.
Replace the calculation logic for up and down with the sum of detections.
Here's a rough guide of how your Svelte script should change:
javascript
<script>
import detections from "../database/getDetections"; // Adjust your import to the new module name
import Carousel from "svelte-carousel";
let colorClass = "";
// Use the detections store
$: detectionCounts = $detections.map(det => det.Count);
$: currentPeople = detectionCounts.reduce((total, count) => total + count, 0); // Sum up all detected counts
// ...
// Other reactive statements and logic
// ...
</script>
In your HTML, you would then use {currentPeople} where you wish to display the count:
This implementation assumes that every document stored in the 'Detections' collection represents a person that is currently in the field of view and should be counted. If your detection system works differently (e.g., if a detection represents an event that increases or decreases the count), you will need to adapt the logic for summing the detection Count accordingly.
Finally, ensure your Firestore collection names in your CV Python script and your Svelte app match and represent the current state of detections as per your application logic.