为什么用相同的功能和输入值绘制的圆会出现不同的颜色?

时间:2019-07-03 04:36:46

标签: python opencv

我正在尝试使用轨迹栏创建具有可调颜色和画笔半径的Paint应用程序。我正在使用鼠标事件来区分拖动和简单移动鼠标。

代码运行,但是,当我尝试在图像窗口上绘制时,有2种不良行为:

  • 基于是通过单击鼠标还是通过拖动鼠标创建圆的不同颜色
  • 图像上边缘的颜色不同

该如何解决?

这是OpenCV练习之一:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_trackbar/py_trackbar.html#trackbar

import numpy as np
import cv2
drawing = False
def nothing(x):
    pass

# Create a black image, a window
img = np.zeros((768,1024,3), np.uint8)
cv2.namedWindow('image')

# create trackbars for color change
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
cv2.createTrackbar('W','image',0,50,nothing)

def draw_brush(event,x,y,flags,param):
    global drawing, b, g, r, w
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        cv2.circle(img,(x,y),w,(b,g,r),-1)
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing == True:
            a, b = x, y
            if a!=x & b!=y:
                cv2.circle(img,(x,y),w,(b,g,r),-1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
# Create a window and bind the function to window
cv2.setMouseCallback('image',draw_brush)

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

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R','image')
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    w = cv2.getTrackbarPos('W','image')

cv2.destroyAllWindows()

screenshot

1 个答案:

答案 0 :(得分:0)

错误在这里

a, b = x, y
if a!=x & b!=y:
    cv2.circle(img,(x,y),w,(b,g,r),-1)

您使用两个变量“ b”。一个作为坐标值,一个作为蓝色值。因此,您的蓝色值在那里获得“ y”坐标值。为“ b”坐标变量使用不同的变量名称。