<jupyter_start><jupyter_text>1. Image pyramids pyramid representation is a type of multi scale signal representation in which a signal or an image is subject to repeated smoothing and subsampling.There are two types of pyramid1. Gaussian pyramid2. Laplacian pyramid  1.1 Gaussian Pyramid<jupyter_code>import cv2
import numpy as np
img = cv2.imread("lena.jpg")
lower_resolution = cv2.pyrDown(img)
lower_resolution1 = cv2.pyrDown(lower_resolution)
upper_resolution = cv2.pyrUp(lower_resolution1)

cv2.imshow("Original Image",img)
cv2.imshow("lower_resolution",lower_resolution)
cv2.imshow("lr1",lower_resolution1)
cv2.imshow("upper_resolution",upper_resolution)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread("lena.jpg")
layer = img.copy()
gp = [layer]
for i in range(6):
    leyer = cv2.pyrDown(layer)
    gp.append(layer)
    cv2.imshow(str(i),layer)
cv2.imshow("Original Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>1.2 Laplacian pyramid A level in Laplacian pyramid is formed by the difference between the level in the gaussian pyramid and expanded version of its upper level in gaussian pyramid<jupyter_code>import cv2
import numpy as np
img = cv2.imread("lena.jpg")
layer = img.copy()
gp = [layer]
for i in range(6):
    leyer = cv2.pyrDown(layer)
    gp.append(layer)
    #cv2.imshow(str(i),layer)
layer = gp[5]
cv2.imshow("last layer gaussian pyramid",layer)
lp = [layer]

for i in range(5,0,-1):
    '''size = (gp[i-1].shape[1], gp[i-1].shape[0])
    print(size)
    print(gp[i].shape)'''
    gaussian_extended = cv2.pyrUp(gp[i])
    laplacian = cv2.subtract(gp[i-1],gaussian_extended)
    cv2.imshow(str(i),laplacian)
cv2.imshow("Original Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output>(512, 512)
(512, 512, 3)<jupyter_text>2. Image blending using pyramid  2.1 Image Blending 1. Load the two images2. gind the Gaussian Pyramids for the two image(apple and orange).in this example,number of levels is 63. From the Gaussian pyramids, find their Laplacian pyramids4. Nnow join the left half of apple and right half of orange in each level of Laplacian pyramids5. Finally from this joint image pyramids reconstruct the original image<jupyter_code>import cv2
import numpy as np
apple = cv2.imread("apple.jpg")
orange = cv2.imread("orange.jpg")
print(apple.shape)
print(orange.shape)
apple_orange = np.hstack((apple[:,:256],orange[:,256:]))
cv2.imshow("apple",apple)
cv2.imshow("orange",orange)
cv2.imshow("apple_orange",apple_orange)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
apple = cv2.imread("apple.jpg")
orange = cv2.imread("orange.jpg")
print(apple.shape)
print(orange.shape)
apple_orange = np.hstack((apple[:,:256],orange[:,256:]))

# generate Gaussian pyramid for apple
apple_copy = apple.copy()
gp_apple = [apple_copy]

for i in range(6):
    apple_copy = cv2.pyrDown(apple_copy)
    gp_apple.append(apple_copy)

    
# generate Gaussian pyramid for orange
orange_copy = orange.copy()
gp_orange = [orange_copy]

for i in range(6):
    orange_copy = cv2.pyrDown(orange_copy)
    gp_orange.append(orange_copy)
    
# generate Laplacian Pyramds for apple
apple_copy = gp_apple[5]
lp_apple = [apple_copy]
for i in range(5,0,-1):
    gaussian_extended = cv2.pyrUp(gp_apple[i])
    laplacian = cv2.subtract(gp_apple[i-1],gaussian_extended)
    lp_apple.append(laplacian)
    
# generate Laplacian Pyramds for orange
orange_copy = gp_orange[5]
lp_orange = [orange_copy]
for i in range(5,0,-1):
    gaussian_extended = cv2.pyrUp(gp_orange[i])
    laplacian = cv2.subtract(gp_orange[i-1],gaussian_extended)
    lp_orange.append(laplacian)    

    
# Now add left and right half of image in each level
apple_orange_pyramid = []
n =0
for apple_lap,orange_lap in zip(lp_apple,lp_orange):
    n+=1
    cols,rows,ch = apple_lap.shape
    laplacian = np.hstack((apple_lap[:,0:int(cols/2)],
                           orange_lap[:,int(cols/2):]))
    apple_orange_pyramid.append(laplacian)

# reconstruct
apple_orange_reconstruct = apple_orange_pyramid[0]
for i in range(1,6):
    apple_orange_reconstruct = cv2.pyrUp(apple_orange_reconstruct)
    apple_orange_reconstruct = cv2.add(apple_orange_pyramid[i],
                                       apple_orange_reconstruct)
    
    
cv2.imshow("apple",apple)
cv2.imshow("orange",orange)
cv2.imshow("apple_orange",apple_orange)
cv2.imshow("apple_orange_reconstruct",apple_orange_reconstruct)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output>(512, 512, 3)
(512, 512, 3)<jupyter_text>3. Contours  3. 1 Contourscontours is a Numpy array of (x,y) coordinates of boundary points of the object.<jupyter_code>import cv2
import numpy as np
img = cv2.imread("opencv-logo.png")
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Image",img)
cv2.imshow("ImageGray",imgray)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread("opencv-logo.png")
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(imgray,127,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,
                                      cv2.CHAIN_APPROX_NONE)

print("number of contours",len(contours))
cv2.drawContours(img,contours,-1,(0,255,0),2)
    
cv2.imshow("Image",img)
cv2.imshow("ImageGray",imgray)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output>number of contours 9<jupyter_text>3.2 motion detection  3.2.1 draw contorus<jupyter_code>import cv2
import numpy as np
cap = cv2.VideoCapture("vtest.avi")
ret,frame1 = cap.read()
ret,frame2 = cap.read()
while cap.isOpened():
    #cv2.imshow("inter",frame)
    diff = cv2.absdiff(frame1,frame2)
    gray = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray,(5,5),0)
    _,thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None,iterations = 3)
    contours,_ = cv2.findContours(dilated,cv2.RETR_TREE,
                                  cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(frame1,contours,-1,(0,255,0),2)
    cv2.imshow("feed",frame1)
    frame1 = frame2
    ret,frame2 = cap.read()
    if cv2.waitKey(40)==27:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>3.2.2 draw person<jupyter_code>import cv2
import numpy as np
#cap = cv2.VideoCapture(0)#"vtest.avi"
cap = cv2.VideoCapture("vtest.avi")
ret,frame1 = cap.read()
ret,frame2 = cap.read()
while cap.isOpened():
    diff = cv2.absdiff(frame1,frame2)
    gray = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray,(5,5),0)
    _,thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None,iterations = 7)
    contours,_ = cv2.findContours(dilated,cv2.RETR_TREE,
                                  cv2.CHAIN_APPROX_SIMPLE)
    
    for contour in contours:
        (x,y,w,h) = cv2.boundingRect(contour)
        if cv2.contourArea(contour)<1200:
            continue
        cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2)
        cv2.putText(frame1,"Status: {}".format('Movement'),
                   (10,20),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
    cv2.imshow("feed",frame1)
    #cv2.imshow("dilated",dilated)
    frame1 = frame2
    ret,frame2 = cap.read()
    if cv2.waitKey(40)==27:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>4 Shape Detection  4.1 Shape Detect<jupyter_code>import cv2
import numpy as np
img = cv2.imread("shapes.png")
img=cv2.resize(img,(500,500))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,240,255,cv2.THRESH_BINARY)
contours,_ = cv2.findContours(thresh,cv2.RETR_TREE,
                             cv2.CHAIN_APPROX_NONE)
print("Number of Contours",len(contours))
for contour in contours:
    approx = cv2.approxPolyDP(contour,
                              0.01*cv2.arcLength(contour,True),
                             True)
    cv2.drawContours(img,[approx],0,(0,0,255),4)
    x = approx.ravel()[0]
    y = approx.ravel()[1] -5
    if len(approx) ==3:
        cv2.putText(img,"TRIANGLE",(x,y),
                   cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
    elif len(approx) ==4:
        x1,y1,w,h = cv2.boundingRect(approx)
        aspectratio = float(w)/h
        print(aspectratio)
        if aspectratio >=0.98 and aspectratio <=1.05:
            cv2.putText(img,"SQUARE",(x,y),
                       cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
        else:
            cv2.putText(img,"RECTANGLE",(x,y),
                       cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
    elif len(approx) ==5:
        cv2.putText(img,"pentagon",(x,y),
                   cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
    elif len(approx) ==10:
        cv2.putText(img,"polygon",(x,y),
                   cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
    else :
        cv2.putText(img,"Circle",(x,y),
                   cv2.FONT_HERSHEY_COMPLEX_SMALL,0.5,(0,0,0))
        
cv2.imshow("shapes",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output>Number of Contours 7
1.0
1.1139240506329113
0.660377358490566<jupyter_text>5. Hough Transform Algorithm The Hough Transform is a popular technique to detect any shape, if you can represent that shape in a mathematical form. It can detect the shape even if it is broken or distroted a little bit. A line in the iamge space can be expressed with two variables.For example:- in the cartesian coordinate system: y = mx+c- in the polar coordinate system xcosΘ + ysinΘ=r (alt+233 for theta value) - Edge deection. eg. using the canny edge detector.- Mapping of edge points to the Hough space and stroage in an accumulator- Interpreatation of the accumulator to yield lines of infinite length. The interpretation is done by thresolding and possibly other constraints.- conversion of infinite lines to finite lines.    - Note: Opencv implements two kind of Hough Line Transforms        - The Standard Houhg Transform (HouhgLines method)        - The probabilistic Hough Line Transform (HoughLinesP method)- x(t) = cos(theta)*r - t*sin(theta), y(t) = sin(theta)*r + t*cos(theta)  5.1 HouhgLines method<jupyter_code>import cv2
import numpy as np
img = cv2.imread("sudoku.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,20,110,apertureSize=3)
lines = cv2.HoughLines(edges,1,np.pi/180,220)
for line in lines:
    rho,theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    # x1 stores the rounded off value of r*cosΘ-1000*sinΘ
    x1 = int(x0+1000*-(b))
    #y1 stores the rounded off r*sinΘ+1000*cosΘ
    y1 = int(y0+1000*(a))
    #x2 stores the rounded off value of r*cosΘ+1000*sinΘ
    x2 = int(x0-1000*-(b))
    #y2 stores the rounded off value of r*sinΘ=1000*cosΘ
    y2 = int(y0-1000*(a))
    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imshow("img",img)
cv2.imshow("canny",edges)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>5.2 HoughLinesP method<jupyter_code>import cv2
import numpy as np
img = cv2.imread("sudoku.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,20,110,apertureSize=3)
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,
                       minLineLength =100,maxLineGap=10)
for line in lines:
    x1,y1,x2,y2 = line[0]
    cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow("img",img)
cv2.imshow("canny",edges)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>6. Road Lane Line Detection  6.1Region of Interest<jupyter_code>%matplotlib qt
import cv2
import numpy as np
import matplotlib.pylab as plt
img = cv2.imread("road_4.jpg")
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
print(img.shape)
height = img.shape[0]
width = img.shape[1]
region_of_interest_vertices = [
    (0,height),(width/2,height/2),
    (width,height)
]

def region_of_interest(img,vertices):
    mask = np.zeros_like(img)
    channel_count = img.shape[2]
    match_mask_color = (255,)*channel_count
    cv2.fillPoly(mask,vertices,match_mask_color)
    masked_image = cv2.bitwise_and(img,mask)
    return masked_image

cropped_image  = region_of_interest(img,
                                   np.array([region_of_interest_vertices],np.int32))



'''cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()'''
plt.imshow(cropped_image)
plt.show()
%matplotlib qt
import cv2
import numpy as np
import matplotlib.pylab as plt


def region_of_interest(img,vertices):
    mask = np.zeros_like(img)
    #channel_count = img.shape[2]
    match_mask_color = 255
    cv2.fillPoly(mask,vertices,match_mask_color)
    masked_image = cv2.bitwise_and(img,mask)
    return masked_image


def drawing_lines(img,lines):
    img = np.copy(img)
    blank_image = np.zeros((img.shape[0],img.shape[1],3),np.uint8)
    for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(blank_image,(x1,y1),(x2,y2),(0,255,0),thickness=3)
    img = cv2.addWeighted(img,0.8,blank_image,1,0.0)
    return img

img = cv2.imread("road_4.jpg")
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
print(img.shape)
height = img.shape[0]
width = img.shape[1]

region_of_interest_vertices = [
    (0,height),(width/2,height/2),
    (width,height)]

gray_image = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
canny_image = cv2.Canny(gray_image,100,200)
cropped_image  = region_of_interest(canny_image,
                                   np.array([region_of_interest_vertices],np.int32))

lines = cv2.HoughLinesP(cropped_image,
                   rho=6,theta=np.pi/60,
                       threshold = 160,lines = np.array([]),
                       minLineLength=40,maxLineGap=25)

res = drawing_lines(img,lines)
    
'''cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()'''
plt.imshow(res)
plt.show()<jupyter_output>(704, 1279, 3)<jupyter_text>6.2 Road Detection on Video<jupyter_code>%matplotlib qt
import cv2
import numpy as np
import matplotlib.pylab as plt


def region_of_interest(img,vertices):
    mask = np.zeros_like(img)
    #channel_count = img.shape[2]
    match_mask_color = 255
    cv2.fillPoly(mask,vertices,match_mask_color)
    masked_image = cv2.bitwise_and(img,mask)
    return masked_image


def drawing_lines(img,lines):
    img = np.copy(img)
    blank_image = np.zeros((img.shape[0],img.shape[1],3),np.uint8)
    for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(blank_image,(x1,y1),(x2,y2),(0,255,0),thickness=8)
    img = cv2.addWeighted(img,0.8,blank_image,1,0.0)
    return img

def process(img):
    
        #img = cv2.imread("road_4.jpg")
        #img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        # print(img.shape)
        height = img.shape[0]
        width = img.shape[1]

        region_of_interest_vertices = [
            (0,height),(width/2,height/2),
            (width,height)]

        gray_image = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
        canny_image = cv2.Canny(gray_image,100,120)
        cropped_image  = region_of_interest(canny_image,
                                           np.array([region_of_interest_vertices],np.int32))

        lines = cv2.HoughLinesP(cropped_image,
                           rho=2,theta=np.pi/180,
                               threshold = 50,lines = np.array([]),
                               minLineLength=40,maxLineGap=100)

        res = drawing_lines(img,lines)
        return res


cap = cv2.VideoCapture("test_video.mp4")
while(cap.isOpened()):
    _,frame = cap.read()
    res = process(frame)
    cv2.imshow("Result",res)
    if cv2.waitKey(1) & 0XFF ==ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
'''cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()'''
#plt.imshow(res)
#plt.show()<jupyter_output><empty_output><jupyter_text>6.3 Detect Circle using Hough Circle<jupyter_code>import cv2
import numpy as np
#img = cv2.imread("shapes.png")
img = cv2.imread("smarties.png")
output = img.copy()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray,5)
circles = cv2.HoughCircles(blur,cv2.HOUGH_GRADIENT,
                          1,20,param1 = 50,param2 = 30,
                          minRadius = 0,maxRadius = 0)


detected_circle = np.uint16(np.around(circles))
for (x,y,r) in detected_circle[0,:]:
    cv2.circle(output,(x,y),r,(0,255,0),2)
    cv2.circle(output,(x,y),2,(0,255,255),2)


cv2.imshow("img",output)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>7. Harris Corner Detector 1. Determine which windows produce very large variations in intensity when moved in both X and Y directions.2. With each such window found, a score R is computed.3. After applying a threshold to this score , important corners are selected and marked.  7.1 Corner Detection<jupyter_code>import cv2
import numpy as np
img = cv2.imread("chessboard.png")
img = cv2.resize(img,(600,600))
cv2.imshow("img",img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,10,7,0.1)
dst = cv2.dilate(dst,None)
img[dst > 0.01 * dst.max()] = [0,0,255]
cv2.imshow("dst",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>7.2 Shi Tomasi Corner Detection<jupyter_code>import cv2
import numpy as np
img = cv2.imread("shapes.png")
img = cv2.resize(img,(600,600))
#cv2.imshow("img",img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray,64,0.01,10)
corners = np.int0(corners)

for i in corners:
    x,y = i.ravel()
    cv2.circle(img,(x,y),3,255,-1)
    
cv2.imshow("dst",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>8. Background Substraction Methods Background Substraction: foreground mask Binary Image containg pixel belonging to the moving object.current_frame - background model ==> add threshold to create foreground mask  8.1 BackgroundSubtractorMOG2<jupyter_code>import cv2
import numpy as np
cap = cv2.VideoCapture("vtest.avi")
fgbg = cv2.createBackgroundSubtractorMOG2()
while cap.isOpened():
    ret,frame = cap.read()
    if frame is None:
        break
    fgmask = fgbg.apply(frame)
    cv2.imshow("fgmask",fgmask)
    cv2.imshow("frame",frame)
    key = cv2.waitKey(30)
    if key == 27:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>8.2 BackgroundSubtractorGMG<jupyter_code>import cv2
import numpy as np
cap = cv2.VideoCapture("vtest.avi")
kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg = cv2.bgsegm_BackgroundSubtractorGMG()
while cap.isOpened():
    ret,frame = cap.read()
    if frame is None:
        break
    fgmask = fgbg.apply(frame)
    fgmask = cv2.morphologyEx(fgmask,cv2.MORPH_OPEN,kernal)
    cv2.imshow("fgmask",fgmask)
    cv2.imshow("frame",frame)
    key = cv2.waitKey(30)
    if key == 27:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>BackgroundSubtractorKNN<jupyter_code>import cv2
import numpy as np
cap = cv2.VideoCapture("vtest.avi")
fgbg = cv2.createBackgroundSubtractorKNN()
while cap.isOpened():
    ret,frame = cap.read()
    if frame is None:
        break
    fgmask = fgbg.apply(frame)
    cv2.imshow("fgmask",fgmask)
    cv2.imshow("frame",frame)
    key = cv2.waitKey(30)
    if key == 27:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Mean Shift Object Tracking<jupyter_code>import cv2
import numpy as np
cap = cv2.VideoCapture("sherman.mp4")
ret,frame = cap.read()

#setup the initial location of window
x,y,width,height = 80,610,122,48

track_window = (x,y,width,height)

#setup the ROI for tracking
roi = frame[y:y+height,x:x+height]
initBB = None
cv2.imshow("ROI",roi)
while True:
    ret,frame = cap.read()
    if ret ==True:
        cv2.imshow("frame",frame)
        key = cv2.waitKey(40)
        if key ==27:
            break
        elif key == ord('s'):
            initBB = cv2.selectROI("frame",frame,fromCenter = False,
                                  showCrosshair = True)
            print(initBB)
    else:
        break
cap.release()
cv2.destroyAllWindows()<jupyter_output>(80, 610, 122, 48)<jupyter_text>Select ROI using Mosue and find the coordinates of it.<jupyter_code>#https://www.pyimagesearch.com/2018/07/30/opencv-object-tracking/
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
tracker = cv2.TrackerCSRT_create()
initBB = None
while cap.isOpened():
    ret,frame = cap.read()
    if ret ==True:
        if initBB is not None:
            (success,box) = tracker.update(frame)
            if success:
                (x,y,w,h) = [int(v) for v in box]
                cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)
            # end if
        # end if
    # end if
        cv2.imshow("frame",frame)
        key = cv2.waitKey(1) & 0XFF
        if key ==27:
            break
        elif key == ord('s'):
            initBB = cv2.selectROI("frame",frame,fromCenter = False,
                                  showCrosshair = True)
            print(initBB)
            tracker.init(frame, initBB)
        elif key == ord("c"):
            initBB = (0,0,0,0)
            x,y,w,h = 0,0,0,0
            tracker.init(frame,initBB)
            print("C button is pressed",initBB)
            (success,box) = tracker.update(frame)
            if success:
                (x,y,w,h) = [int(v) for v in box]
                cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)
    else:
        break
cap.release()
cv2.destroyAllWindows()
import numpy as np
import cv2
import sys
import copy
import time


def main_1(video):
    framecount = 0
    vid =  cv2.VideoCapture(video)
    background2 = cv2.BackgroundSubtractorMOG2(history=200, nmixtures=5, backgroundRatio=0.01)
    kernel = np.array(([0,1,0],[1,1,1],[0,1,0]),dtype = np.uint8)
    kernel2 = np.ones((10,10),np.uint8)
    kernel3 = np.ones((8,8),np.uint8)
    new = 0
    old = 0
    count = 0

    cv2.namedWindow("mask")
    cv2.moveWindow("mask",0,0)
    cv2.namedWindow("foreground")
    cv2.moveWindow("foreground", 1000,0)
    cv2.namedWindow("original")    
    while vid.isOpened():
        framecount = framecount + 1
        ret, frame = vid.read()
        if not ret:
            break
        imgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        mask = background2.apply(frame,learningRate=.05)
        erode = cv2.erode(mask,kernel,iterations =1)
        dilate = cv2.dilate(erode,kernel2,iterations = 1)

        ret,thresh = cv2.threshold(dilate,127,255,0)
        contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

        if framecount>150:
            for i in contours:
                if cv2.contourArea(i) > 2000:
                    x,y,w,h = cv2.boundingRect(i)
                    if y+h/2>400:
                        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
                        new = new + y+h/2

            if new > old +400:
                count = count + 1
                print ("_____________________________________")
                print ("new", new, "old", old, "count", count)
            number = str(count)
            cv2.putText(frame,number,(700,100),cv2.FONT_HERSHEY_SIMPLEX,4,(0,0,255),10)
            old = new
            new = 0

            
            cv2.imshow('mask', mask)
            #cv2.imshow('foreground',dilate)
            #cv2.imshow('original',frame)
        #time.sleep(.025)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
    vid.release()

    cv2.destroyAllWindows()
main_1("sherman.mp4")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1323529411764706, 'fraction_numerical': 0.04841040462427745, 'mean_word_length': 3.488553987027852, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 78, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '232865', 'license': 'Apache-2.0', 'n_tokens_mistral': 9350, 'n_tokens_neox': 8768, 'n_words': 1628, 'path': 'exercise_6.ipynb', 'repo_name': 'deepak223098/Computer_Vision_Example', 'size': '23528'}