DSatishchandra commited on
Commit
3f43833
Β·
verified Β·
1 Parent(s): dfd57a1

Update models/object_detection.py

Browse files
Files changed (1) hide show
  1. models/object_detection.py +31 -24
models/object_detection.py CHANGED
@@ -1,33 +1,40 @@
1
- from transformers import pipeline
2
- import cv2
 
3
 
4
- # Use Hugging Face's pipeline for object detection
5
- def load_yolov5():
6
- # Load pre-trained YOLOv5 model for object detection (use Hugging Face-compatible model if YOLOv5 is available)
7
- model = pipeline("object-detection", model="ultralytics/yolov5") # Hugging Face hosted YOLOv5 model (if available)
8
- return model
 
 
 
 
 
9
 
10
- def detect_faults(video):
11
  """
12
- Detect faults like cracks, dirt, etc. in the given video using YOLOv5 model.
13
  Args:
14
- - video (cv2.VideoCapture): Input video or image file
15
-
16
  Returns:
17
- - result (list): List of detected faults with confidence scores
18
  """
19
- model = load_yolov5() # Load the model
20
- faults = []
21
- while True:
22
- ret, frame = video.read()
23
- if not ret:
24
- break
25
- # Run the model on the frame
26
- results = model(frame)
27
- result = results # Assuming the result contains detected faults with bounding boxes and labels
28
- faults.append(result)
29
 
30
- video.release()
31
- return faults
32
 
 
 
 
33
 
 
 
1
+ from transformers import AutoModelForObjectDetection, AutoImageProcessor
2
+ import torch
3
+ from PIL import Image
4
 
5
+ def load_huggingface_model():
6
+ """
7
+ Load a pre-trained object detection model from Hugging Face.
8
+ For example, we are using Facebook's DETR (Detection Transformer).
9
+ """
10
+ # Load a Hugging Face pre-trained model for object detection
11
+ model = AutoModelForObjectDetection.from_pretrained("facebook/detr-resnet-50")
12
+ processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")
13
+
14
+ return model, processor
15
 
16
+ def detect_faults_from_huggingface(image_path):
17
  """
18
+ Detect faults in the given image using Hugging Face's model (DETR in this case).
19
  Args:
20
+ - image_path (str): Path to the image file
21
+
22
  Returns:
23
+ - results (list): Detected objects and their confidence scores.
24
  """
25
+ model, processor = load_huggingface_model()
26
+
27
+ # Load image
28
+ image = Image.open(image_path)
29
+
30
+ # Preprocess the image
31
+ inputs = processor(images=image, return_tensors="pt")
 
 
 
32
 
33
+ # Run the model
34
+ outputs = model(**inputs)
35
 
36
+ # Post-process the output to get detections
37
+ target_sizes = torch.tensor([image.size[::-1]]) # Reversing the image size (height, width)
38
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
39
 
40
+ return results