Virtual Paint

We are going to benefit from ColorDetection and Contours/Shape Detection

Lists that we are going to use (all of them are nested lists)

  • myColours = [...]

  • myColourValues = [...]

  • myPoints = [...]

Functions that we are going to write

  • def findColour(img, myColours)

  • def getContours(img)

  • def drawOnCanvas(myPoints, myColourValues)

import cv2
import numpy as np

cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
cap.set(10, 150)

myColours = [[107, 66, 0, 118, 164, 255],
             [63, 0, 108, 87, 40, 166]]

myColourValues = [[204, 0, 204],
                [0, 102, 0]]          ##BGR

myPoints = []       # [x, y, colorID]

def findColour(img, myColours, myColourValues):
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    count = 0
    newPoints = []
    for color in myColours:
        lower = np.array([color[0:3]])
        upper = np.array([color[3:6]])
        mask = cv2.inRange(imgHSV, lower, upper)
        x,y = getContours(mask)
        cv2.circle(imageResult, (x, y), 10, myColourValues[count], cv2.FILLED)
        if x != 0 and y != 0:
            newPoints.append([x, y, count])
        count += 1
        #cv2.imshow(str(color[0]), mask)
    return newPoints

def getContours(img):
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    x,y,w,h = 0,0,0,0
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 500:
            #cv2.drawContours(imageResult, cnt, -1, (255, 0, 0), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            x, y, w, h = cv2.boundingRect(approx)
    return x+(w//2), y

def drawOnCanvas(myPoints, myColourValues):
    for point in myPoints:
        cv2.circle(imageResult, (point[0], point[1]), 10, myColourValues[point[2]], cv2.FILLED)

while True:
    success, img = cap.read()
    imageResult = img.copy()
    newPoints = findColour(img, myColours, myColourValues)
    if len(newPoints) != 0:
        for newP in newPoints:
            myPoints.append(newP)
    if len(myPoints) != 0:
        drawOnCanvas(myPoints, myColourValues)
    cv2.imshow("Result", imageResult)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Last updated