I thought i understood global variable scope in python.  

But my counter is not giving what i expect.
Im using opencv events to capture mouse click and release, and i only want to do a write to an output if the variable is 1, so i need it to be as expected.

**Warnings reported:**

```
SyntaxWarning: name 'roicounter' is assigned to before global declaration
SyntaxWarning: name 'imgcounter' is assigned to before global declaration

```

**Expected Output**

```
imgcounter: 1
roicounter: 1
imgcounter: 1
roicounter: 2
imgcounter: 2
roicounter: 1
imgcounter: 2
roicounter: 2

```

**Output Received (the roicounter strictly increases with time)**

```
roidcounter before reset: 0
roidcounter after reset: 0
roidcounter before increment on any event: 0
roidcounter after increment: 1
1
roidcounter before increment: 1
roidcounter after increment: 2
2
roidcounter before increment: 2
roidcounter after increment: 3
3

```

Ouput received: After one rectangle drawn:

```
imgcounter: 1
roidcounter after buttonup (if > 1): 262
roidcounter before increment: 262
roidcounter after increment: 263
263

```

**Code**

```
import cv2
import glob

refPt = []
cropping = False
outputfil = "labels.txt"
global imgcounter, roidcounter
imgcounter = 0
roidcounter = 0

def click_and_crop(event, x, y, flags, param):
    global refPt, cropping, imgcounter, roidcounter
    print("roidcounter before increment: "+str(roidcounter))
    roidcounter+=1
    print("roidcounter after increment: "+str(roidcounter))
    print(roidcounter)

    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True
    elif event == cv2.EVENT_LBUTTONUP:
        refPt.append((x, y))
        cropping = False

        # draw a rectangle around the region of interest
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)
        print("imgcounter: "+str(imgcounter))
        # write to output
        if roidcounter > 1:
           print("roidcounter after buttonup (if > 1): "+str(roidcounter))
        else:
           print("othet stuff")
           print("roidcounter after buttonup (else): "+str(roidcounter))
           #write roi data
fils=glob.glob("*.jpg")
for fil in fils:
    print("inloop")
    imgcounter+=1
    print("roidcounter before reset: "+str(roidcounter))
    roidcounter = 0
    print("roidcounter after reset: "+str(roidcounter))
    globalfil = fil
    #write to output
    image = cv2.imread(fil)
    clone = image.copy()
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", click_and_crop)

    while True:
        cv2.imshow("image", image)
        key = cv2.waitKey(1) & 0xFF

        if key == ord("r"):
            image = clone.copy()

        elif key == ord("c"):
            break

    cv2.destroyAllWindows()

```