Computer vision 1

Heb je een webcam? Dan is het leuk om die te gebruiken. Download anders dit filmpje hier Maak in je IDE een nieuw project / map aan, noem het python-computer-vision. Kies een logische locatie op je harde schijf hiervoor zodat je de code niet over een week kwijt bent. Maak een nieuw bestand aan met de titel jouw-naam-computer-vision.py.

fromhere
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
import cv2 import numpy as np # Initialize webcam cap = cv2.VideoCapture(0) # Define A4 paper aspect ratio (W/H ≈ 0.707) A4_RATIO = 0.707 # (210mm / 297mm) def find_a4_contour(contours): for cnt in contours: # Approximate the contour peri = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) # Look for 4-point contours if len(approx) == 4: # Get bounding box and check aspect ratio x, y, w, h = cv2.boundingRect(approx) if w == 0 or h == 0: continue aspect_ratio = float(w) / float(h) if 0.65 < aspect_ratio < 0.75: return approx return None while True: ret, frame = cap.read() if not ret: break # Preprocess gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) edges = cv2.Canny(blur, 50, 150) # Find contours contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Detect A4 paper a4_contour = find_a4_contour(contours) if a4_contour is not None: cv2.drawContours(frame, [a4_contour], -1, (0, 255, 0), 3) cv2.putText(frame, "A4 Detected", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # Show output cv2.imshow("A4 Detector", frame) # Exit on 'q' if cv2.waitKey(1) & 0xFF == ord('q'): break # Cleanup cap.release() cv2.destroyAllWindows()

Navigatie

« Camera ready Groep splitsen wel of geen python »