Spaces:
Sleeping
Sleeping
Create obstruction_detector.py
Browse files- obstruction_detector.py +54 -0
obstruction_detector.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2 as cv
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.signal import find_peaks
|
| 4 |
+
|
| 5 |
+
class ObstructionDetector:
|
| 6 |
+
def __init__(self, threshold=500):
|
| 7 |
+
self.threshold = threshold
|
| 8 |
+
|
| 9 |
+
def preprocess_image(self, image):
|
| 10 |
+
# Convert the image to grayscale if it's a color image
|
| 11 |
+
if len(image.shape) == 3:
|
| 12 |
+
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
|
| 13 |
+
|
| 14 |
+
# Apply Gaussian blur to reduce noise
|
| 15 |
+
preprocessed_image = cv.GaussianBlur(image, (5, 5), 0)
|
| 16 |
+
|
| 17 |
+
# Perform other preprocessing steps as needed (e.g., contrast adjustment, histogram equalization)
|
| 18 |
+
|
| 19 |
+
return preprocessed_image
|
| 20 |
+
|
| 21 |
+
def plot_histogram(self, image):
|
| 22 |
+
# Calculate the histogram
|
| 23 |
+
histogram = cv.calcHist([image], [0], None, [256], [0, 256])
|
| 24 |
+
|
| 25 |
+
# Smoothing the histogram using a simple moving average (window size = 5)
|
| 26 |
+
kernel = np.ones((5, 1)) / 5
|
| 27 |
+
smoothed_histogram = cv.filter2D(histogram, -1, kernel)
|
| 28 |
+
|
| 29 |
+
return smoothed_histogram
|
| 30 |
+
|
| 31 |
+
def count_histogram_peaks(self, smoothed_histogram):
|
| 32 |
+
# Find peaks in the smoothed histogram with frequency greater than the threshold
|
| 33 |
+
peaks, _ = find_peaks(smoothed_histogram.flatten(), height=self.threshold)
|
| 34 |
+
return peaks
|
| 35 |
+
|
| 36 |
+
def detect_obstruction(self, img_path):
|
| 37 |
+
# Load the image
|
| 38 |
+
img = cv.imread(img_path)
|
| 39 |
+
|
| 40 |
+
# Preprocess the image
|
| 41 |
+
preprocessed_img = self.preprocess_image(img)
|
| 42 |
+
|
| 43 |
+
# Count the number of peaks in the smoothed histogram above the threshold
|
| 44 |
+
smoothed_histogram = self.plot_histogram(preprocessed_img)
|
| 45 |
+
peaks = self.count_histogram_peaks(smoothed_histogram)
|
| 46 |
+
|
| 47 |
+
# Check if peaks are too close together
|
| 48 |
+
peak_spacing = np.diff(peaks)
|
| 49 |
+
if len(peak_spacing) == 0 or np.all(peak_spacing < 10):
|
| 50 |
+
report = "A imagem NÃO contém obstrução significativa | e NÃO possui múltiplas distribuições de densidade claramente distintas."
|
| 51 |
+
else:
|
| 52 |
+
report = "A imagem contém obstrução significativa | possui múltiplas distribuições de densidade claramente distintas."
|
| 53 |
+
|
| 54 |
+
return report
|