akhfzl commited on
Commit
cf2a4ae
·
verified ·
1 Parent(s): 915c3ff

upload_app

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import torch
4
+ import sys
5
+ import pathlib
6
+ temp = pathlib.PosixPath
7
+ pathlib.PosixPath = pathlib.WindowsPath
8
+
9
+ yolov5_path = pathlib.PosixPath('yolov5')
10
+ sys.path.append(str(yolov5_path))
11
+
12
+ from models.experimental import attempt_load
13
+ from utils.general import non_max_suppression, scale_boxes
14
+
15
+ model = attempt_load('best.pt')
16
+ model.eval()
17
+ pathlib.PosixPath = temp
18
+
19
+ cap = cv2.VideoCapture(0)
20
+
21
+ while cap.isOpened():
22
+ ret, frame = cap.read()
23
+ if not ret:
24
+ print("Failed to grab frame")
25
+ break
26
+
27
+ # Resize the frame to 640x640
28
+ img = cv2.resize(frame, (640, 640))
29
+ img = img[:, :, ::-1] # Convert BGR to RGB
30
+ img = np.ascontiguousarray(img) # Make sure the array is contiguous
31
+ img = torch.from_numpy(img).float() # Convert to Tensor
32
+ img /= 255.0 # Normalize to [0, 1]
33
+
34
+ # Change the shape to [batch_size, channels, height, width]
35
+ img = img.permute(2, 0, 1).unsqueeze(0) # Rearrange dimensions and add batch dimension
36
+
37
+ # Perform inference
38
+ with torch.no_grad():
39
+ pred = model(img)[0] # Get predictions
40
+
41
+ # Apply Non-Maximum Suppression
42
+ pred = non_max_suppression(pred, conf_thres=0.25, iou_thres=0.45)
43
+
44
+ # Process predictions
45
+ for det in pred: # detections per image
46
+ if det is not None and len(det):
47
+ # Rescale boxes from 640 to original frame size
48
+ det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], frame.shape).round()
49
+
50
+ # Draw bounding boxes on the frame
51
+ for *xyxy, conf, cls in reversed(det):
52
+ label = f'{model.names[int(cls)]}: {conf:.2f}' # Create label
53
+ cv2.rectangle(frame, (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3])), (0, 255, 0), 2) # Draw box
54
+ cv2.putText(frame, label, (int(xyxy[0]), int(xyxy[1] - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Draw label
55
+
56
+ # Display the frame
57
+ cv2.imshow('Deteksi Cadar Masker', frame)
58
+
59
+ # Break the loop on 'q' key press
60
+ if cv2.waitKey(1) & 0xFF == ord('q'):
61
+ break
62
+
63
+ # Release the webcam and close windows
64
+ cap.release()
65
+ cv2.destroyAllWindows()