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



你可能感兴趣的:(OpenCv-python,opencv,python)