I want to create a Paint application with adjustable colors and brush radius using Trackbars.
I have written the code for this as follows:
import cv2
import numpy as np
def nothing(x):
pass
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),ra,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),ra,(0,0,255),-1)
img = np.zeros((1024,1024,3), np.uint8)
cv2.namedWindow('trackbar')
cv2.createTrackbar('Red','trackbar',0,255,nothing)
cv2.createTrackbar('Green','trackbar',0,255,nothing)
cv2.createTrackbar('Blue','trackbar',0,255,nothing)
cv2.createTrackbar('Radius','trackbar',10,200,nothing)
ra = 0
switch = '0 : OFF\n1 : ON'
cv2.createTrackbar(switch,'trackbar',0,1,nothing)
while(1):
cv2.imshow('trackbar', img)
ra = cv2.getTrackbarPos('Radius', 'trackbar')
cv2.setMouseCallback('trackbar', draw_circle)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
r = cv2.getTrackbarPos('Red','trackbar')
g = cv2.getTrackbarPos('Green', 'trackbar')
b = cv2.getTrackbarPos('Blue', 'trackbar')
s = cv2.getTrackbarPos(switch, 'trackbar')
if s==0:
img[:] = 0
else:
img[:] = [b,g,r]
cv2.destroyAllWindows()
But it is not working properly. Trackbar for changing RBG color is working but the circle and rectangle are not drawn on mouse click. Anyone can tell me what i am doing wrong in this code?