|
| 1 | +from cv2 import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +# Capturing Video through webcam. |
| 5 | +cap = cv2.VideoCapture(0) |
| 6 | + |
| 7 | +while(1): |
| 8 | + _, img = cap.read() |
| 9 | + |
| 10 | + # converting frame(img) from BGR (Blue-Green-Red) to HSV (hue-saturation-value) |
| 11 | + hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) |
| 12 | + |
| 13 | + # defining the range of Yellow color |
| 14 | + red_lower = np.array([0, 100, 100], np.uint8) |
| 15 | + red_upper = np.array([2, 255, 255], np.uint8) |
| 16 | + red = cv2.inRange(hsv, red_lower, red_upper) |
| 17 | + |
| 18 | + # Morphological transformation, Dilation |
| 19 | + kernal = np.ones((5, 5), "uint8") |
| 20 | + res = cv2.bitwise_and(img, img, mask=red) |
| 21 | + |
| 22 | + # Tracking Colour (Yellow) |
| 23 | + (contours, hierarchy) = cv2.findContours( |
| 24 | + red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) |
| 25 | + |
| 26 | + for pic, contour in enumerate(contours): |
| 27 | + area = cv2.contourArea(contour) |
| 28 | + if(area > 900): |
| 29 | + |
| 30 | + x, y, w, h = cv2.boundingRect(contour) |
| 31 | + img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 3) |
| 32 | + |
| 33 | + # show color detection result |
| 34 | + cv2.imshow("Color Tracking", img) |
| 35 | + cv2.imshow("Red", res) |
| 36 | + |
| 37 | + if cv2.waitKey(10) & 0xFF == 27: |
| 38 | + cap.release() |
| 39 | + cv2.destroyAllWindows() |
| 40 | + break |
0 commit comments