OpenCV-Python官方文档中文翻译9:Trackbar as the Color Palette跟踪条作为调色板

本文介绍如何利用OpenCV中的Trackbar功能创建一个简单应用,该应用允许用户通过滑动跟踪条来调整并显示BGR颜色。通过cv.createTrackbar()函数创建跟踪条,并设置回调函数。此外,还展示了如何将Trackbar用作开关,只有当开关开启时应用才会显示颜色。最后,提出了一个练习,要求读者使用Trackbar创建一个可调节颜色和画笔半径的绘图应用。
摘要由CSDN通过智能技术生成

Trackbar as the Color Palette

Goal

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

  1. Create a Paint application with adjustable colors and brush radius using trackbars. For drawing, refer previous tutorial on mouse handling.

用trackbar创建一个颜色和画笔半径可调的绘图应用。对于绘图,请参考以前关于鼠标处理的课程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值