|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +frameWidth = 640 |
| 5 | +frameHeight = 480 |
| 6 | +cap = cv2.VideoCapture(0) |
| 7 | +cap.set(3, frameWidth) |
| 8 | +cap.set(4, frameHeight) |
| 9 | +cap.set(10, 150) |
| 10 | + |
| 11 | +myColors = [[5, 107, 0, 19, 255, 255], # orange |
| 12 | + [133, 56, 0, 159, 156, 255], # purple |
| 13 | + [57, 76, 0, 100, 255, 255], # green |
| 14 | + [90, 48, 0, 118, 255, 255]] # blue |
| 15 | + |
| 16 | +myColorValues = [[51, 153, 255], # BGR |
| 17 | + [255, 0, 255], |
| 18 | + [0, 255, 0], |
| 19 | + [255, 0, 0]] |
| 20 | + |
| 21 | +myPoints = [] ## [x , y , colorId ] |
| 22 | + |
| 23 | + |
| 24 | +def findColor(img, myColors, myColorValues): |
| 25 | + imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) |
| 26 | + count = 0 |
| 27 | + newPoints = [] |
| 28 | + for color in myColors: |
| 29 | + lower = np.array(color[0:3]) |
| 30 | + upper = np.array(color[3:6]) |
| 31 | + mask = cv2.inRange(imgHSV, lower, upper) |
| 32 | + x, y = getContours(mask) |
| 33 | + cv2.circle(imgResult, (x, y), 15, myColorValues[count], cv2.FILLED) |
| 34 | + if x != 0 and y != 0: |
| 35 | + newPoints.append([x, y, count]) |
| 36 | + count += 1 |
| 37 | + # cv2.imshow(str(color[0]),mask) |
| 38 | + return newPoints |
| 39 | + |
| 40 | + |
| 41 | +def getContours(img): |
| 42 | + contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) |
| 43 | + x, y, w, h = 0, 0, 0, 0 |
| 44 | + for cnt in contours: |
| 45 | + area = cv2.contourArea(cnt) |
| 46 | + if area > 500: |
| 47 | + # cv2.drawContours(imgResult, cnt, -1, (255, 0, 0), 3) |
| 48 | + peri = cv2.arcLength(cnt, True) |
| 49 | + approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) |
| 50 | + x, y, w, h = cv2.boundingRect(approx) |
| 51 | + return x + w // 2, y |
| 52 | + |
| 53 | + |
| 54 | +def drawOnCanvas(myPoints, myColorValues): |
| 55 | + for point in myPoints: |
| 56 | + cv2.circle(imgResult, (point[0], point[1]), 10, myColorValues[point[2]], cv2.FILLED) |
| 57 | + |
| 58 | + |
| 59 | +while True: |
| 60 | + success, img = cap.read() |
| 61 | + imgResult = img.copy() |
| 62 | + newPoints = findColor(img, myColors, myColorValues) |
| 63 | + if len(newPoints) != 0: |
| 64 | + for newP in newPoints: |
| 65 | + myPoints.append(newP) |
| 66 | + if len(myPoints) != 0: |
| 67 | + drawOnCanvas(myPoints, myColorValues) |
| 68 | + |
| 69 | + cv2.imshow("Result", imgResult) |
| 70 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 71 | + break |
| 72 | + |
| 73 | +cap.release() |
| 74 | +cv2.destroyAllWindows() |
0 commit comments