nehulagrawal commited on
Commit
0b3f0b4
·
verified ·
1 Parent(s): 8174ce5

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +129 -0
main.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import mss
4
+ import cv2
5
+ import numpy as np
6
+ import time
7
+ import glob
8
+ from ultralytics import YOLO
9
+ from openpyxl import Workbook
10
+
11
+ # Ensure necessary directories exist
12
+ save_path = "/home/ml/ML/ml_backup/arjun/"
13
+ screenshots_path = os.path.join(save_path, "screenshots")
14
+ detect_path = os.path.join(save_path, "runs/detect/")
15
+
16
+ os.makedirs(save_path, exist_ok=True)
17
+ os.makedirs(screenshots_path, exist_ok=True)
18
+
19
+ # Define pattern classes
20
+ classes = ['Head and shoulders bottom', 'Head and shoulders top', 'M_Head', 'StockLine', 'Triangle', 'W_Bottom']
21
+
22
+ # Load YOLOv8 model
23
+ model_path = "/home/ml/ML/ml_backup/arjun/best111.pt"
24
+ if not os.path.exists(model_path):
25
+ raise FileNotFoundError(f"Model file not found: {model_path}")
26
+ model = YOLO(model_path)
27
+
28
+ # Define screen capture region
29
+ monitor = {"top": 0, "left": 683, "width": 683, "height": 768}
30
+
31
+ # Create an Excel file
32
+ excel_file = os.path.join(save_path, "classification_results.xlsx")
33
+ wb = Workbook()
34
+ ws = wb.active
35
+ ws.append(["Timestamp", "Predicted Image Path", "Label"]) # Headers
36
+
37
+ # Initialize video writer
38
+ video_path = os.path.join(save_path, "annotated_video.mp4")
39
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
40
+ fps = 0.5 # Adjust frames per second as needed
41
+ video_writer = None
42
+
43
+ # Start capturing
44
+ with mss.mss() as sct:
45
+ start_time = time.time()
46
+ last_capture_time = start_time # Track the last capture time
47
+ frame_count = 0
48
+
49
+ while True:
50
+ # Continuously capture the screen
51
+ sct_img = sct.grab(monitor)
52
+ img = np.array(sct_img)
53
+ img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
54
+
55
+ # Check if 60 seconds have passed since last YOLO prediction
56
+ current_time = time.time()
57
+ if current_time - last_capture_time >= 60:
58
+ # Take screenshot for YOLO prediction
59
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
60
+ image_name = f"predicted_images_{timestamp}_{frame_count}.png"
61
+ image_path = os.path.join(screenshots_path, image_name)
62
+ cv2.imwrite(image_path, img)
63
+
64
+ # Run YOLO model and get save directory
65
+ results = model(image_path, save=True)
66
+ predict_path = results[0].save_dir if results else None
67
+
68
+ # Find the latest annotated image inside predict_path
69
+ if predict_path and os.path.exists(predict_path):
70
+ annotated_images = sorted(glob.glob(os.path.join(predict_path, "*.jpg")), key=os.path.getmtime, reverse=True)
71
+ final_image_path = annotated_images[0] if annotated_images else image_path
72
+ else:
73
+ final_image_path = image_path # Fallback to original image
74
+
75
+ # Determine predicted label
76
+ if results and results[0].boxes:
77
+ class_indices = results[0].boxes.cls.tolist()
78
+ predicted_label = classes[int(class_indices[0])]
79
+ else:
80
+ predicted_label = "No pattern detected"
81
+
82
+ # Insert data into Excel (store path instead of image)
83
+ ws.append([timestamp, final_image_path, predicted_label])
84
+
85
+ # Read the image for video processing
86
+ annotated_img = cv2.imread(final_image_path)
87
+ if annotated_img is not None:
88
+ # Add timestamp and label text to the image
89
+ font = cv2.FONT_HERSHEY_SIMPLEX
90
+ cv2.putText(annotated_img, f"{timestamp}", (10, 30), font, 0.7, (0, 255, 0), 2, cv2.LINE_AA)
91
+ cv2.putText(annotated_img, f"{predicted_label}", (10, 60), font, 0.7, (0, 255, 255), 2, cv2.LINE_AA)
92
+
93
+ # Initialize video writer if not already initialized
94
+ if video_writer is None:
95
+ height, width, layers = annotated_img.shape
96
+ video_writer = cv2.VideoWriter(video_path, fourcc, fps, (width, height))
97
+
98
+ video_writer.write(annotated_img)
99
+
100
+ print(f"Frame {frame_count}: {final_image_path} -> {predicted_label}")
101
+ frame_count += 1
102
+
103
+ # Update the last capture time
104
+ last_capture_time = current_time
105
+
106
+ # Save the Excel file periodically
107
+ wb.save(excel_file)
108
+
109
+ # If you want to continuously display the screen, you can add this line
110
+ cv2.imshow("Screen Capture", img)
111
+
112
+ # Break if 'q' is pressed (you can exit the loop this way)
113
+ if cv2.waitKey(1) & 0xFF == ord('q'):
114
+ break
115
+
116
+ # Release video writer
117
+ if video_writer is not None:
118
+ video_writer.release()
119
+ print(f"Video saved at {video_path}")
120
+
121
+ # Remove all files in screenshots directory
122
+ for file in os.scandir(screenshots_path):
123
+ os.remove(file.path)
124
+ os.rmdir(screenshots_path)
125
+
126
+ print(f"Results saved to {excel_file}")
127
+
128
+ # Close OpenCV window
129
+ cv2.destroyAllWindows()