|
| 1 | +import cv2 |
| 2 | +import os |
| 3 | +import time |
| 4 | + |
| 5 | +cascade_path = cv2.data.haarcascades + "haarcascade_russian_plate_number.xml" |
| 6 | +plate_cascade = cv2.CascadeClassifier(cascade_path) |
| 7 | + |
| 8 | +if plate_cascade.empty(): |
| 9 | + raise IOError("Error loading Haar cascade") |
| 10 | + |
| 11 | +# Output directory |
| 12 | +os.makedirs("plates", exist_ok=True) |
| 13 | + |
| 14 | +cap = cv2.VideoCapture(0) |
| 15 | +if not cap.isOpened(): |
| 16 | + raise IOError("Cannot open webcam") |
| 17 | + |
| 18 | +plate_count = 0 |
| 19 | +last_save_time = 0 |
| 20 | +save_delay = 0.5 |
| 21 | + |
| 22 | +while True: |
| 23 | + ret, frame = cap.read() |
| 24 | + if not ret: |
| 25 | + break |
| 26 | + |
| 27 | + frame = cv2.resize(frame, (960, 540)) |
| 28 | + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
| 29 | + gray = cv2.equalizeHist(gray) |
| 30 | + gray = cv2.bilateralFilter(gray, 11, 17, 17) |
| 31 | + |
| 32 | + roi = gray[270:540, :] |
| 33 | + plates = plate_cascade.detectMultiScale( |
| 34 | + roi, |
| 35 | + scaleFactor=1.05, |
| 36 | + minNeighbors=7, |
| 37 | + minSize=(60, 20) |
| 38 | + ) |
| 39 | + |
| 40 | + current_time = time.time() |
| 41 | + |
| 42 | + for (x, y, w, h) in plates: |
| 43 | + y += 270 |
| 44 | + aspect_ratio = w / h |
| 45 | + |
| 46 | + if 2 < aspect_ratio < 5: |
| 47 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
| 48 | + |
| 49 | + if current_time - last_save_time > save_delay: |
| 50 | + plate_count += 1 |
| 51 | + plate_img = frame[y:y+h, x:x+w] |
| 52 | + cv2.imwrite(f"plates/plate_{plate_count}.jpg", plate_img) |
| 53 | + last_save_time = current_time |
| 54 | + |
| 55 | + cv2.imshow("Number Plate Detection", frame) |
| 56 | + |
| 57 | + if cv2.waitKey(1) & 0xFF == ord("q"): |
| 58 | + break |
| 59 | + |
| 60 | +cap.release() |
| 61 | +cv2.destroyAllWindows() |
0 commit comments