Learn practical skills, build real-world projects, and advance your career
!pip install jovian --upgrade --quiet
import jovian
jovian.commit(project = 'virtual-paint')
[jovian] Attempting to save notebook.. [jovian] Detected Kaggle notebook... [jovian] Uploading notebook to https://jovian.ml/saffafatima12/virtual-paint

## Importing the libraries ##

import cv2
import numpy as np    
  


## Stacking function from Murtaza Hassan's video ## 

def stackImages(scale,imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank]*rows
        hor_con = [imageBlank]*rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        ver = hor
    return ver





## Just an empty function ###

def empty(a):
    pass


## Path for image ##

path = 'cute_robo.jpg'


## Create a new window for placing the trackbars ##

cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)


## Creating the min/max trackbars for hue, sat, and values ##

cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",19,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",110,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",240,255,empty)
cv2.createTrackbar("Val Min","TrackBars",153,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)
 


## Loop for displaying values from trackbars in real time ##

while True:
    img = cv2.imread(path)
    imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    
    h_min = cv2.getTrackbarPos("Hue Min","TrackBars")
    h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
    s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
    s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
    v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
    v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
    
    print(h_min,h_max,s_min,s_max,v_min,v_max)  ### Checking if values are getting displayed correctly
    
    lower = np.array([h_min,s_min,v_min])       ### Storing values in np arrays
    upper = np.array([h_max,s_max,v_max])
    
    
   
    mask = cv2.inRange(imgHSV,lower,upper)      ### Creating a mask
    imgResult = cv2.bitwise_and(img,img,mask=mask)
 
 
   
    imgStack = stackImages(0.4,([img,imgHSV],[mask,imgResult]))
    cv2.imshow("Stacked Images", imgStack)
    cv2.waitKey(1)


## Define a get contour function ##

def getContours(img):
    
    contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    ### Arguments in the .findContours() -- first argument is the image source, 
    ### second is the contour retrieval method, and third is contour completion method.
    ### Link for details in official documentation: https://docs.opencv.org/trunk/d4/d73/tutorial_py_contours_begin.html
    
    for cnt in contours:
        area = cv2.contourArea(cnt) ## prints area of the shape bounded by the contour
        print(area)
        
        if area > 500:
          cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)  ## Draws contours 
        
          peri = cv2.arcLength(cnt,True)                         ## for drawing bounding rectangle
          approx = cv2.approxPolyDP(cnt,0.1*peri,True) ## the 0.1*perimeter adjusts the bounding box shape
          print(len(approx))
          x, y, w, h = cv2.boundingRect(approx)
          cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)
 
       
    
## Other things ##

path = 'shapes_2.jpg'
img = cv2.imread(path)
imgContour = img.copy()  ## Creating a copy to prevent the original image from being overwritten
 
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ## For converting image to gray scale
imgBlur = cv2.GaussianBlur(imgGray,(7,7),1)    ## For blurring the image slightly
imgCanny = cv2.Canny(imgBlur,50,50)            ## For making edges appear sharper
getContours(imgCanny)                          ## Using the get contour func to get contours
 
imgBlank = np.zeros_like(img)
imgStack = stackImages(0.6,([img,imgGray,imgBlur],
                            [imgCanny,imgContour,imgBlank]))
 
cv2.imshow("Stack", imgStack)
cv2.waitKey(0)

Checking webcam is set up properly