|
| 1 | +# Importing libraries |
| 2 | +import cv2 |
| 3 | +import imutils |
| 4 | + |
| 5 | +# Values to parse |
| 6 | +redLower = (161, 155, 84) |
| 7 | +redUpper = (179, 255, 255) |
| 8 | +text = "Nothing Found" |
| 9 | + |
| 10 | +# Initialising Camera |
| 11 | +camera = cv2.VideoCapture(0) |
| 12 | + |
| 13 | +while True: |
| 14 | + |
| 15 | + # Read the Frame from the camera |
| 16 | + (grabbed, frame) = camera.read() |
| 17 | + |
| 18 | + # Controlling the Framesize |
| 19 | + frame = imutils.resize(frame, width=600) |
| 20 | + |
| 21 | + # Applying Image Smoothning |
| 22 | + blurred = cv2.GaussianBlur(frame, (11, 11), 0) |
| 23 | + |
| 24 | + # Converting Image to HSV |
| 25 | + hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) |
| 26 | + |
| 27 | + # Masking the Image inbetween the bounds |
| 28 | + mask = cv2.inRange(hsv, redLower, redUpper) |
| 29 | + |
| 30 | + # Applying FX for closing any gaps |
| 31 | + mask = cv2.erode(mask, None, iterations=2) |
| 32 | + mask = cv2.dilate(mask, None, iterations=2) |
| 33 | + |
| 34 | + # Finding the hits |
| 35 | + cnts = cv2.findContours( |
| 36 | + mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] |
| 37 | + center = None |
| 38 | + |
| 39 | + # There is a hit |
| 40 | + if len(cnts) > 0: |
| 41 | + c = max(cnts, key=cv2.contourArea) |
| 42 | + |
| 43 | + # Get the circle coordinates |
| 44 | + ((x, y), radius) = cv2.minEnclosingCircle(c) |
| 45 | + |
| 46 | + # Get the Middle point |
| 47 | + M = cv2.moments(c) |
| 48 | + center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) |
| 49 | + |
| 50 | + if radius > 10: |
| 51 | + # Draw the circles around the object |
| 52 | + cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) |
| 53 | + cv2.circle(frame, center, 5, (0, 0, 255), -1) |
| 54 | + |
| 55 | + # Print Signs according to the radius |
| 56 | + if radius > 250: |
| 57 | + text = "Stop" |
| 58 | + else: |
| 59 | + if (center[0] < 150): |
| 60 | + text = "Left" |
| 61 | + elif (center[0] > 250): |
| 62 | + text = "Right" |
| 63 | + elif (radius < 250): |
| 64 | + text = "Go" |
| 65 | + else: |
| 66 | + text = "Stop" |
| 67 | + |
| 68 | + # Render the text onto screen |
| 69 | + cv2.putText(frame, text, (10, 20), |
| 70 | + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) |
| 71 | + |
| 72 | + # Show the Frame from the camera |
| 73 | + cv2.imshow("Frame", frame) |
| 74 | + |
| 75 | + # Stop the program when the Q key is pressed |
| 76 | + key = cv2.waitKey(1) & 0xFF |
| 77 | + if key == ord('q'): |
| 78 | + break |
| 79 | + |
| 80 | +# Release the camera and destroy all windows |
| 81 | +camera.release() |
| 82 | +cv2.destroyAllWindows() |
0 commit comments