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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import cv2 import numpy as np
cap = cv2.VideoCapture(0) rectangle_area = 0 circle_area = 0 line_length = 0
while True: ret, frame = cap.read() if not ret: print("Failed to read frame from the camera.") break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 200, 400)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours: area = cv2.contourArea(contour)
if area < 100: continue
approx = cv2.approxPolyDP(contour, 0.04 * cv2.arcLength(contour, True), True) if len(approx) == 4: cv2.drawContours(frame, [approx], 0, (0, 255, 0), 2) cv2.putText(frame, f"Rectangle Area: {area}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) rectangle_area = area elif len(approx) == 3: cv2.drawContours(frame, [approx], 0, (255, 0, 0), 2) triangle_area = cv2.contourArea(contour) cv2.putText(frame, f"Triangle Area: {triangle_area}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
elif len(approx) > 6: (x, y), radius = cv2.minEnclosingCircle(contour) cv2.circle(frame, (int(x), int(y)), int(radius), (0, 0, 255), 2) circle_area = int(np.pi * radius * radius) cv2.putText(frame, f"Circle Area: {circle_area}", (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) all_area = rectangle_area / circle_area cv2.putText(frame, f"Area: {all_area}", (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
elif len(approx) == 2: x1, y1 = approx[0][0] x2, y2 = approx[1][0] line_length = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 2) cv2.putText(frame, f"Line Length: {line_length}", (10, 190), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("Shapes", frame)
if cv2.waitKey(1) & 0xFF == ord('q'): break
cap.release() cv2.destroyAllWindows()
|