Trackbar as the Color Palette
Goal
- Learn to bind trackbar to OpenCV windows
- You will learn these functions : cv.getTrackbarPos(), cv.createTrackbar() etc.
- 学习如何将跟踪条与OpenCV窗口绑定
- 你将学习这些功能: cv.getTrackbarPos(), cv.createTrackbar() 等等
Code Demo
Here we will create a simple application which shows the color you specify. You have a window which shows the color and three trackbars to specify each of B,G,R colors. You slide the trackbar and correspondingly window color changes. By default, initial color will be set to Black.
For cv.createTrackbar() function, first argument is the trackbar name, second one is the window name to which it is attached, third argument is the default value, fourth one is the maximum value and fifth one is the callback function which is executed every time trackbar value changes. The callback function always has a default argument which is the trackbar position. In our case, function does nothing, so we simply pass.
Another important application of trackbar is to use it as a button or switch. OpenCV, by default, doesn’t have button functionality. So you can use trackbar to get such functionality. In our application, we have created one switch in which application works only if switch is ON, otherwise screen is always black.
这里我们将创建一个简单的应用,用来展示你指定的颜色。你拥有一个窗口,将展示颜色和三个指明B,G,R颜色的跟踪条。你滑动跟踪条,相应地窗口颜色改变。默认的,初始颜色设置为黑色。
对于 cv.createTrackbar() 函数,第一个参数是跟踪条的名字,第二个是它连接的窗口的名字,第三个是默认值,第四个是最大值,第五个是每次跟踪条值改变执行的回调函数。回调函数总有一个默认参数,该参数是跟踪条的位置。在我们的例子中,函数什么都不干,所以我们简单地跳过。
跟踪条另一个重要的用法就是作为按钮或者开关。OpenCV默认没有按钮功能。所以你可以用trackbar来得到这样的功能。在我们的应用中,我们创建一个开关,只有开关打开的时候应用才工作,否则屏幕将一直是黑色。
import numpy as np
import cv2 as cv
def nothing(x):
pass
#Create a black image,a window
img = np.zeros((300,512,3),np.uint8)
cv.namedWindow("image")
#create trackbars for color change
cv.createTrackbar("R","image",0,255,nothing)
cv.createTrackbar("G","image",0,255,nothing)
cv.createTrackbar("B","image",0,255,nothing)
#create switch for ON/OFF functionality
switch = "0:OFF\n1:ON"
cv.createTrackbar(switch,"image",0,1,nothing)
while(1):
cv.imshow("image",img)
k = cv.waitKey(1)&0xFF
if k ==27:
break
#get current positions of four trackbars
r = cv.getTrackbarPos("R","image")
g = cv.getTrackbarPos("G","image")
b = cv.getTrackbarPos("B","image")
s = cv.getTrackbarPos(switch,"image")
if s == 0:
img[:] = 0
else:
img[:] = [b,g,r]
cv.destroyAllWindows()
The screenshot of the application looks like below :
应用截屏如下所示:
Exercises
- Create a Paint application with adjustable colors and brush radius using trackbars. For drawing, refer previous tutorial on mouse handling.
用trackbar创建一个颜色和画笔半径可调的绘图应用。对于绘图,请参考以前关于鼠标处理的课程。