0% found this document useful (0 votes)
5 views4 pages

Scratch Detection in Images Using YOLO

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Scratch Detection in Images Using YOLO

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Scratch-Not Scratch detection in images:

# ======================
# STEP 1: Import Libraries
# ======================
import os
import numpy as np
import cv2
from [Link] import SVC
from [Link] import make_pipeline
from [Link] import StandardScaler
from sklearn.model_selection import train_test_split
from [Link] import classification_report
import [Link] as plt
from collections import Counter
from [Link] import local_binary_pattern
from ultralytics import YOLO

# ======================
# STEP 2: Global Config
# ======================
DATASET_DIR = 'C:/Users/Admin/PycharmProjects/PythonProject/Dataset'
CATEGORIES = ["scratch", "non_scratch"]
IMAGE_SIZE = (400, 400)
sift = cv2.SIFT_create()
yolo_model = YOLO("[Link]")

# ======================
# STEP 3: LBP Filter Function
# ======================
def lbp_filter(image, radius=1, n_points=8):
lbp = local_binary_pattern(image, n_points, radius, method="uniform")
lbp = [Link](lbp, None, 0, 255, cv2.NORM_MINMAX)
return [Link](np.uint8)

# ======================
# STEP 4: Feature Extraction
# ======================
features = []
labels = []
print("[INFO] Extracting SIFT + LBP features...")

for label in CATEGORIES:


folder = [Link](DATASET_DIR, label)
for filename in [Link](folder):
path = [Link](folder, filename)
try:
img = [Link](path)
img = [Link](img, IMAGE_SIZE)
gray = [Link](img, cv2.COLOR_BGR2GRAY)
filtered = lbp_filter(gray)
kp, desc = [Link](filtered, None)

if desc is not None:


pooled_desc = [Link](desc, axis=0)
[Link](pooled_desc)
[Link](label)
else:
print(f"[WARNING] No SIFT features in {filename}")

except Exception as e:
print(f"[WARNING] Skipping {filename}: {e}")

X = [Link](features)
y = [Link](labels)

print(f"[INFO] Loaded {len(X)} images")


print("Class distribution:", Counter(y))

# ======================
# STEP 5: Train SVM Model
# ======================
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)

clf = make_pipeline(StandardScaler(), SVC(kernel='rbf', probability=True))


[Link](X_train, y_train)
print("[INFO] SVM training complete")
# ======================
# STEP 6: Evaluate Model
# ======================
print("[INFO] Evaluating classifier...")
y_pred = [Link](X_test)
print(classification_report(y_test, y_pred, zero_division=0))

# ======================
# STEP 7: Test Function
# ======================
def test_image(img_path):
try:
img = [Link](img_path)
img = [Link](img, IMAGE_SIZE)
gray = [Link](img, cv2.COLOR_BGR2GRAY)
filtered = lbp_filter(gray)
kp, desc = [Link](filtered, None)

if desc is not None:


pooled_desc = [Link](desc, axis=0)
prediction = [Link]([pooled_desc])[0]
else:
print("[ERROR] No SIFT features found")
return

label = "Scratch Detected" if prediction == "scratch" else "No Scratch"


color = 'red' if prediction == "scratch" else 'green'

display_img = [Link](img, cv2.COLOR_BGR2RGB)


[Link](figsize=(5, 5))
[Link](display_img)
[Link](label, color=color, fontsize=16)
[Link]('off')
[Link]()

except Exception as e:
print(f"[ERROR] Failed to process image: {e}")

# ======================
# STEP 8: YOLO Detection
# ======================
def detect_scratch_yolo(img_path):
results = yolo_model(img_path)
boxes = results[0].boxes
names = results[0].names
image = [Link](img_path)

for box in boxes:


x1, y1, x2, y2 = map(int, [Link][0])
cls_name = names[int([Link])]
conf = float([Link])
print(f"[YOLO] {cls_name} ({conf:.2f})")

[Link](image, (x1, y1), (x2, y2), (0, 255, 0), 2)


[Link](image, f"{cls_name} {conf:.2f}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)

[Link](figsize=(6, 6))
[Link]([Link](image, cv2.COLOR_BGR2RGB))
[Link]('off')
[Link]()

# ======================
# STEP 9: Run Tests
# ======================
test_image(r"C:\Users\Admin\PycharmProjects\PythonProject\Dataset\non_scratch\[Link]")
detect_scratch_yolo(r"C:\Users\Admin\PycharmProjects\PythonProject\Dataset\non_scratch\ergt
.jpeg")

You might also like