title: Drawing circle of variable radius using mouse in Python OpenCV
body: <p>My question is with reference to <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html#more-advanced-demo" rel="nofollow">this tutorial</a>.
  In the above tutorial, whenever we drag the mouse pointer, a circle of constant radius (ie. 5 pixels) is drawn. </p>
  
  <p>I want to draw a circle, having radius equal to the distance dragged by mouse left click. Also want to show the preview when the mouse pointer is being moved after Left Button is down. Similar to what happens in MS Paint.</p>
  
  <pre><code>import cv2
  import numpy as np
  
  drawing=False
  mode=True   # True--&gt; Rectangle , False --&gt; Circle
  
  ix,iy=-1,-1
  
  def draw_fig(event,x,y,flags,param):
      global ix,iy,drawing,mode,img
  
      if event==cv2.EVENT_LBUTTONDOWN:
          drawing=True
          ix,iy=x,y
          if(not mode):#ie. Drawing Mode==Circle
              backup=img
  
      elif event==cv2.EVENT_MOUSEMOVE:
          if (drawing):
              if(mode):
                  cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
              else:
                  #Resetting Canvas
                  #img=np.zeros((512,512,3),np.uint8)
                  #cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
                  #Showing Circle Preview
                  cv2.circle(backup,(x,y),max(abs(ix-x),abs(iy-y)),(0,0,255),-1)
  
      elif event==cv2.EVENT_LBUTTONUP:
          if(drawing):
              drawing=False
              if(mode):
                  cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
              else:
                  #Resetting Canvas
                  img=np.zeros((512,512,3),np.uint8)
                  cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
                  #Showing Circle Preview
                  cv2.circle(backup,(x,y),max(abs(ix-x),abs(iy-y)),(0,0,255),-1)
                  img=backup
  
  img=np.zeros((512,512,3),np.uint8)
  cv2.namedWindow('image')
  cv2.setMouseCallback('image',draw_fig)
  font = cv2.FONT_HERSHEY_SIMPLEX
  cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
  
  while(1):
      cv2.imshow('image',img)
      k=cv2.waitKey(1)
      if(k==ord('m')):
          mode=not mode
      elif k==27:
          break
      elif k==ord('r'):
          img=np.zeros((512,512,3),np.uint8)
          cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
  
  cv2.destroyAllWindows()
  </code></pre>
  
  <p>But its showing me an error : </p>
  
  <blockquote>
    <p>UnboundLocalError: local variable 'backup' referenced before
    assignment</p>
  </blockquote>
  
  <p>Can anyone tell me what I am doing wrong and any alternate way to achieve this?</p>