How to fix increase of memory usage of python script?

I have a memory usage issue with my script. Script keeps increasing memory usage in time. I have tried using garbage collector and deleting variables manually. I moved many variables outside of the loop and decleared them as global. I have decreased memory usage increase from 25 - 75 MB to 0.1 MB. Is there any leaks in my code? If there is how I can fix it?

Thanks in advance...

import win32gui, win32ui, win32con, win32api, cv2, numpy, keyboard, os
from PIL import Image
from datetime import datetime
from time import sleep

date = ""
current = datetime.now()

WINDOWTITLE = 'BlueStacks App Player'
RUNNING = False

XSIZE = 244
YSIZE = 407

currentStateX = 210
currentStateY = 373

lookRed = [(247,67,74),(240,65,72),(246,67,73), (245,66,73), (242,66,72), (243,66,73)]
lookGreen = [(0,249,60), (0,250,61)]

searchButton = cv2.imread('images/searchButton.png')
startFight = cv2.imread('images/startFight.png')
backButton = cv2.imread('images/backButton.png')

rCircleText = cv2.imread('images/redCircleText.png')
gCircleText = cv2.imread('images/greenCircleText.png')

emulatorWindow = win32gui.FindWindow(None, WINDOWTITLE)
sizeWindow = emulatorWindow
emulatorWindow = win32gui.GetWindow(emulatorWindow, win32con.GW_CHILD)

if emulatorWindow == 0:
    input("There is no such window as '"+WINDOWTITLE+"'. Please start the emulator and the game to start the bot. Press any key to exit...")
    exit(1)

def setRunning():
    global RUNNING

    RUNNING = False if RUNNING==True else True

def checkCaptcha():
    global lookRed, lookGreen
    red = False

    im = Image.open('images/currentState.png')
    pix = im.load()

    if checkImage(rCircleText) != (0,0):
        print(getDate(), "Found red captcha requested.")
        red = True
    elif checkImage(gCircleText) != (0,0):
        print(getDate(), "Found green captcha requested.")
        red = False
    else:
        return
    
    input("CAPTCHA SOLVING REQUESTED.")
    
    for x in range(currentStateX):
        for y in range(currentStateY):
            if red:
                if pix[x,y] in lookRed:
                    click(x,y)
            elif not red:
                if pix[x,y] in lookGreen:
                    click(x,y)
    
def getDate():
    global date, current
    date = "["
    current = datetime.now()

    #Date Part
    if len(str(current.year)) < 2:
        date += "0" + str(current.year)
    else:
        date += str(current.year)

    date += ":"

    if len(str(current.month)) < 2:
        date += "0" + str(current.month)
    else:
        date += str(current.month)

    date += ":"

    if len(str(current.day)) < 2:
        date += "0" + str(current.day)    
    else:
        date += str(current.day)

    date += "]"

    #Minute Part
    date += "["

    if len(str(current.hour)) < 2:
        date += "0" + str(current.hour)
    else:
        date += str(current.hour)

    date += ":"

    if len(str(current.minute)) < 2:
        date += "0" + str(current.minute)
    else:
        date += str(current.minute)

    date += ":"

    if len(str(current.second)) < 2:
        date += "0" + str(current.second)    
    else:
        date += str(current.second)

    date += "]:"

    return date

def setWindowSize(x0, y0):
    global sizeWindow
    win32gui.MoveWindow(sizeWindow, x0, y0, XSIZE, YSIZE, True)
    sleep(2)

def checkWindowSize():
    global sizeWindow
    x0, y0, x1, y1 = win32gui.GetWindowRect(sizeWindow)

    w = x1 - x0
    h = y1 - y0

    # print("W:",w,"H:",h)
    # return

    if w != XSIZE and h != YSIZE:
        setWindowSize(x0, y0)

def checkImage(searchImage):
    currentState = cv2.imread('images/currentState.png')

    if currentState.size == 0:
        return

    h, w = searchImage.shape[:-1]

    result = cv2.matchTemplate(currentState, searchImage, cv2.TM_CCOEFF_NORMED)

    threshold = .8
    loc = numpy.where(result >= threshold)

    if loc[0].size == 0 and loc[1].size == 0:
        return (0,0)

    for pt in zip(*loc[::-1]):
        cv2.rectangle(currentState, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    return (pt[0] + (w/2), pt[1] + (h/2))

def updateCurrent():
    global emulatorWindow, currentStateX ,currentStateY

    wDC = win32gui.GetWindowDC(emulatorWindow)
    dcObj=win32ui.CreateDCFromHandle(wDC)
    cDC=dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, currentStateX, currentStateY)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(currentStateX, currentStateY) , dcObj, (0,0), win32con.SRCCOPY)
    dataBitMap.SaveBitmapFile(cDC, 'images/currentState.png')
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(emulatorWindow, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

def click(x, y):
    global emulatorWindow, sizeWindow
    lParam = win32api.MAKELONG(x, y)


    win32gui.SendMessage(sizeWindow, win32con.WM_ACTIVATE, win32con.WA_CLICKACTIVE, 0)

    win32api.PostMessage(emulatorWindow, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    win32api.PostMessage(emulatorWindow, win32con.WM_LBUTTONUP, None, lParam)

def botLoop():
    if not RUNNING:
        print(getDate(), "Script is paused. Press Ctrl+x to continue...", end="\r")
        return
    else:
        os.system('cls')

    position = (0, 0)

    #Check for the search button
    while position == (0, 0):
        print(getDate(),"Searching for search aliens button...",end="\r")
        position = checkImage(searchButton)
        updateCurrent()
        checkCaptcha()

    print()
    print(getDate(),"Found the search aliens button. Clicking...\n")
    click(int(position[0]), int(position[1]))
    position = (0, 0)

    #Check for the start fight button
    while position == (0, 0):
        print(getDate(),"Searching for start fight button...",end="\r")
        position = checkImage(startFight)
        updateCurrent()
    
    print()
    print(getDate(),"Found the start fight button. Clicking...\n")  
    click(int(position[0]), int(position[1]))
    position = (0, 0)

    #Check for the back button
    while position == (0, 0):
        print(getDate(),"Searching for back button...",end="\r")
        position = checkImage(backButton)
        updateCurrent()

    print()
    print(getDate(),"Found the back button. Clicking...\n")  
    click(int(position[0]), int(position[1]))

keyboard.add_hotkey("ctrl+x", setRunning)
input("Press any key to start the script...")
RUNNING = True

checkWindowSize()
updateCurrent()

os.system('cls')

position = (0, 0)

while True:
    botLoop()

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum