OpenCV-Pythonは、マウスで円を描き矩形を描き、パレットで円と矩形の色を修正します


import numpy as np
import cv2
ix, iy = -1, -1  #        

#       
events = [i for i in dir(cv2) if 'EVENT' in i]
print(events)


#           
def nothing(x):
    pass


#       
def manage(event, x, y, flags, param):
    global ix, iy

    #         
    r = cv2.getTrackbarPos('R', 'image')
    g = cv2.getTrackbarPos('G', 'image')
    b = cv2.getTrackbarPos('B', 'image')
    color = [b, g, r]  #            color        

    #       
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.rectangle(img, (ix, iy), (x, y), color, 2)  #        
    elif event == cv2.EVENT_RBUTTONDOWN:
        cv2.circle(img, (x, y), 23, color, 2)  #       


#          
img = np.zeros((400, 600, 3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image', manage)  #         

#      
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
img[:] = 255  #            

while (1):
    cv2.imshow('image', img)  #       
    k = cv2.waitKey(1) & 0XFF
    if k == 27:  #    Esc     
        break