Upload ZeroDefect YOLOv5 package (weights, ONNX, RKNN, metadata)
Browse filesFiles changed (7)
- .gitattributes+1
- README.md+119-3
- best.onnxAdded+3
- best.ptAdded+3
- best.rknnAdded+3
- data.yamlAdded+12
- infer_onnx.pyAdded+164
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textbest.rknn filter=lfs diff=lfs merge=lfs -text
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119---license: mittags:- object-detection- pytorch- yolov5- onnx- rknn- rv1106- luckfox- aircraft-inspection- edge-aimetrics:- precision- recall- mapmodel-index:- name: Zerodefect-1.0results:- task:type: object-detectionname: Object Detectiondataset:type: customname: Merged Aircraft Skin Defect & Corrosion Datasetmetrics:- type: precisionvalue: 0.428name: Precision- type: recallvalue: 0.358name: Recall- type: mapvalue: 0.319name: mAP@0.5- type: mapvalue: 0.235name: mAP@0.5:0.95---# ZeroDefect YOLOv5 Nano Model### Optimized Object Detection for Aircraft Skin Inspections (Edge-Deployable)This repository contains the trained weights, ONNX export, and compiled RKNN model for detection of surface defects on aircraft skin. It is optimized for edge deployment on low-cost hardware like the **Luckfox Pico Max (RV1106 SoC with 0.5 TOPS NPU)**.## 📊 Classes & Keywords MapThe model detects the following **7 categories** of defects:1. `crack` — Structural cracks, fatigue lines2. `dent` — Impact dents, surface deformations3. `corrosion` — Rust, chemical wear, oxidation4. `scratch` — Superficial scrapes, paint scratches5. `paint-peel` — Flaking paint, coating degradation6. `missing-head` — Missing rivet heads or fasteners7. `defect` — Generic surface defect anomalies---## 📈 Training & Validation Metrics* **Model Architecture**: YOLOv5 Nano (`yolov5n.pt` backbone)* **Epochs**: 150* **Dataset Size**: 22k+ training images, 2.2k+ validation images (unified from 36 COCO sources)* **Validation Performance**:* **Precision**: `0.428`* **Recall**: `0.358`* **mAP@0.5**: `0.319`* **mAP@0.5:0.95**: `0.235`### Category mAP@0.5 Highlights:* `missing-head` (rivets): **0.526*** `dent`: **0.441*** `scratch`: **0.355*** `paint-peel`: **0.311*** `crack`: **0.276**---## 📁 Repository Contents* `best.pt` — PyTorch model weights (YOLOv5 format, ~3.8 MB)* `best.onnx` — Exported ONNX model graph (opset 12, simplified, ~7.2 MB)* `best.rknn` — Compiled RKNN binary optimized for RV1106 NPU (INT8 quantized, ~2.6 MB)* `data.yaml` — Dataset metadata configuration* `infer_onnx.py` — Simple python script to run inference on custom images using `best.onnx`---## 🚀 Quick Start: ONNX Inference (Python)To run inference on a local image using the ONNX model, download `best.onnx` and `infer_onnx.py` and run:```bashpip install onnxruntime opencv-python numpypython infer_onnx.py --model best.onnx --image test.jpg --conf 0.25```---## 📟 Hardware Deployment (Luckfox Pico Max / RV1106 NPU)The `best.rknn` model is pre-compiled and quantized to **INT8** for direct execution on the RV1106 NPU.1. **Push model to the board**:```bashadb push best.rknn /userdata/```2. **Cross-compile the C++ inference runner**:Compile the YOLOv5 demo from `rknn_model_zoo` using the RV1106 GCC toolchain:```bash./build-linux.sh -t rv1106 -a armv7l -d yolov5```3. **Execute on board**:```bash./rknn_yolov5_demo /userdata/best.rknn test.jpg```---## 📜 LicenseThis model is released under the **MIT License**.
123version https://git-lfs.github.com/spec/v1oid sha256:fc2a70634e8df86c0890b4b455bf2fa0aec22c1790ee214659149b45c4b5bf05size 7513583123version https://git-lfs.github.com/spec/v1oid sha256:add51aa71cf5dc72d4ae72072d1f36f2a0a64a2a0d7ab8f8d14faeac5ffd636dsize 3778031123version https://git-lfs.github.com/spec/v1oid sha256:a6682605a433a6f067ce3e104ad2e6a7810879be080f24074033a3fbdc0cfc98size 2748405123456789101112path: ./
train: images/train
val: images/val
nc: 7
names:
- crack
- dent
- corrosion
- scratch
- paint-peel
- missing-head
- defect123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import argparse
import cv2
import numpy as np
import onnxruntime as ort
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=False, scaleFill=False, scaleup=True, stride=32):
# Resize and pad image while meeting stride-multiple constraints
shape = im.shape[:2] # current shape [height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
# Scale ratio (new / old)
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup: # only scale down, do not scale up (for better val mAP)
r = min(r, 1.0)
# Compute padding
ratio = r, r # width, height ratios
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
if auto: # minimum rectangle
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
elif scaleFill: # stretch
dw, dh = 0.0, 0.0
new_unpad = new_shape[1], new_shape[0]
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
dw /= 2 # divide padding into 2 sides
dh /= 2
if shape[::-1] != new_unpad: # resize
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
return im, ratio, (dw, dh)
def xywh2xyxy(x):
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
y = np.copy(x)
y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x
y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y
return y
def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None):
# Runs Non-Maximum Suppression (NMS) on inference results
nc = prediction.shape[2] - 5 # number of classes
xc = prediction[..., 4] > conf_thres # candidates
# Settings
max_wh = 7680 # maximum box width and height
max_det = 300 # maximum detections per image
redundant = True # require redundant detections
multi_label = nc > 1 # multiple labels per box (adds AMAP of class overlap)
output = [np.zeros((0, 6))] * prediction.shape[0]
for xi, x in enumerate(prediction): # image index, image inference
x = x[xc[xi]] # confidence filter
if not x.shape[0]:
continue
# Compute candidate box coordinates [x1, y1, x2, y2]
box = xywh2xyxy(x[:, :4])
# Confidences & class probabilities
conf = x[:, 4:5]
class_prob = x[:, 5:]
j = np.argmax(class_prob, axis=1, keepdims=True)
c_prob = np.take_along_axis(class_prob, j, axis=1)
# Filter detections by confidence score
x = np.concatenate((box, c_prob * conf, j.astype(np.float32)), axis=1)
x = x[x[:, 4] > conf_thres]
if not x.shape[0]:
continue
# Sort by confidence
x = x[x[:, 4].argsort()[::-1]]
# Batched NMS
c = x[:, 5:6] * max_wh # class offset
boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
# Compute NMS using OpenCV
indices = cv2.dnn.NMSBoxes(
bboxes=boxes.tolist(),
scores=scores.tolist(),
score_threshold=conf_thres,
nms_threshold=iou_thres
)
if len(indices) > 0:
if isinstance(indices, np.ndarray):
indices = indices.flatten()
x = x[indices[:max_det]]
output[xi] = x
return output
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, required=True, help="ONNX model path")
parser.add_argument("--image", type=str, required=True, help="Input image path")
parser.add_argument("--output", type=str, default="output.jpg", help="Output image path")
parser.add_argument("--conf", type=float, default=0.25, help="Confidence threshold")
parser.add_argument("--iou", type=float, default=0.45, help="IoU threshold")
args = parser.parse_args()
# Load image
img0 = cv2.imread(args.image)
if img0 is None:
print(f"Error: Could not read image {args.image}")
return
# Letterbox resize
img, ratio, (dw, dh) = letterbox(img0, new_shape=(640, 640), auto=False)
# Preprocess
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img).astype(np.float32) / 255.0 # normalize
if len(img.shape) == 3:
img = np.expand_dims(img, 0)
# ONNX session
session = ort.InferenceSession(args.model)
input_name = session.get_inputs()[0].name
outputs = session.run(None, {input_name: img})
# Run NMS
detections = non_max_suppression(outputs[0], conf_thres=args.conf, iou_thres=args.iou)[0]
# Classes
classes = ["crack", "dent", "corrosion", "scratch", "paint-peel", "missing-head", "defect"]
colors = [
(0, 0, 255), (0, 255, 0), (255, 0, 0),
(0, 255, 255), (255, 0, 255), (255, 255, 0), (128, 128, 128)
]
# Scale boxes back to original image size
if len(detections) > 0:
detections[:, [0, 2]] -= dw
detections[:, [1, 3]] -= dh
detections[:, :4] /= ratio[0]
# Draw boxes
for det in detections:
x1, y1, x2, y2, conf, cls = det
x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
cls_id = int(cls)
label = f"{classes[cls_id]} {conf:.2f}"
color = colors[cls_id % len(colors)]
cv2.rectangle(img0, (x1, y1), (x2, y2), color, 2)
cv2.putText(img0, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
cv2.imwrite(args.output, img0)
print(f"🎉 Saved detection result to {args.output} (found {len(detections)} defects)")
if __name__ == "__main__":
main().gitattributes+1
README.md+119-3
best.onnxAdded+3
best.ptAdded+3
best.rknnAdded+3
data.yamlAdded+12
infer_onnx.pyAdded+164