[Reproduced] OpenCV+Python uses the track bar as a palette (9)

I believe anyone who has been in touch with Java knows the track bar. It is called a slider control in Java. Today we will also implement it in OpenCV as a basic study.

Here, we will create a simple application to display the specified color. We will create a window to display colors, and three tracking bars for specifying B, G, and R colors. Slide the track bar and change the window color accordingly. By default, the initial color will be set to black.

We need to understand several functions:

createTrackbar(const string& trackbarname, const string&winname, int* value, int count ,TrackbarCallback onChange = 0, void* userdata = 0)

For the cv.createTrackbar() function, its parameters are defined as:

Parameter 1: Track bar name

Parameter 2: Window name

Parameter 3: Initial position of the slider

Parameter 4: the value that represents the maximum position of the slider

Parameter 5: The default value is 0, which points to the callback function

Parameter 6: The default value is 0, the data value passed by the user to the callback function

getTrackbarPos(const string& trackbarname, const string& winname)

Function role:

Get the value of the position of the slider

Parameter 1: progress bar name

Parameter 2: Window name

Return value: progress bar position

getTrackbarPos( trackbarname,winname )

Parameter definition:

trackbarname-the name of the trackbar.

winname-the name of the parent window of the track bar.

This function returns the current position of the specified track bar.

Another important application of the track bar is to use it as a button or switch. By default, OpenCV does not have button functions. Therefore, we can use the track bar to get such functions. In the application, we created a switch, the application can only run when the switch is ON, otherwise the screen is always black.

Now look at the code:

	view plaincopy to clipboardprint?
1. import numpy as np  
2. import cv2 as cv  
3. def nothing(x):  
4.     pass  
5. # Create a black image, a window  
6. img = np.zeros((300,512,3), np.uint8)  
7. cv.namedWindow('image')  
8. # create trackbars for color change  
9. cv.createTrackbar('R','image',0,255,nothing)  
10.cv.createTrackbar('G','image',0,255,nothing)  
11.cv.createTrackbar('B','image',0,255,nothing)  
12.# create switch for ON/OFF functionality  
13.switch = '0 : OFF \n1 : ON'  
14.cv.createTrackbar(switch, 'image',0,1,nothing)  
15.while(1):  
16.    cv.imshow('image',img)  
17.    k = cv.waitKey(1) & 0xFF  
18.    if k == 27:  
19.        break  
20.    # get current positions of four trackbars  
21.    r = cv.getTrackbarPos('R','image')  
22.    g = cv.getTrackbarPos('G','image')  
23.    b = cv.getTrackbarPos('B','image')  
24.    s = cv.getTrackbarPos(switch,'image')  
25.    if s == 0:  
26.        img[:] = 0  
27.    else:  
28.        img[:] = [b,g,r]  
29.cv.destroyAllWindows()  

We can see the effect:
Insert picture description here

Of course, this is only a color palette that can be adjusted. We have already talked about the function of using the mouse as a brush in OpenCV. Now let's create a drawing board and use the track bar to change the color of the brush, similar to Our computer's "drawing" software is the same.

In the previous tutorial, we used EVENT_FLAG_LBUTTON to indicate the current left button of the mouse is pressed, EVENT_MOUSEMOVE to indicate the mouse movement, and cv2.circle as the brush. In the last tutorial, our default pen color is red, and the penultimate parameter is the color representation, the code is:

cv2.circle(img, (x, y), 1, [0, 0, 255], 1)

But in this tutorial, in order to change the color of the brush at any time, we need to pass in dynamic variables;

cv2.circle(img, (x, y), 1, [b, g, r], 1)

b, g, r are determined by the track bar:

cv2.createTrackbar(‘R’, ‘image’, 0, 255, callback)

cv2.createTrackbar(‘B’, ‘image’, 0, 255, callback)

cv2.createTrackbar(‘G’, ‘image’, 0, 255, callback)

We must also note that for OpenCV, its color format is BGR, not RGB, so we need to pass in the parameters correctly.

Now we look at the code:

	view plaincopy to clipboardprint?
1. import cv2  
2. import numpy as np  
3.   
4. def callback(object):  
5.    pass  
6.  
7. img = np.zeros((400, 400, 3), np.uint8)  
cv2.namedWindow('image')  
8.  
9. switch = '0:OFF\n1:ON'  
10.cv2.createTrackbar(switch, 'image', 0, 1, callback)  
11.  
12.cv2.createTrackbar('R', 'image', 0, 255, callback)  
13.cv2.createTrackbar('B', 'image', 0, 255, callback)  
14.cv2.createTrackbar('G', 'image', 0, 255, callback)  
15.  
16.def Mouseback(event, x, y, flags, param):  
17.    if flags == cv2.EVENT_FLAG_LBUTTON and event == cv2.EVENT_MOUSEMOVE:  
18.        cv2.circle(img, (x, y), 1, [b, g, r], 1)  
19.  
20.img[:] = [255, 255, 255]  
21.  
22.while(True):  
23.    r = cv2.getTrackbarPos('R', 'image')  
24.    g = cv2.getTrackbarPos('G', 'image')  
25.    b = cv2.getTrackbarPos('B', 'image')  
26.    if cv2.getTrackbarPos(switch, 'image') == 1:  
27.        cv2.setMouseCallback('image', Mouseback)  
28.    else:  
29.        img[:] = [255, 255, 255]  
30.    if cv2.waitKey(10) & 0xFF == ord('q'):  
31.        break  
32.    cv2.imshow('image', img)  
33.cv2.destroyAllWindows()  

Experimental effect:
Insert picture description here

Press the Q key to exit, we can see that the color of the brush can be changed at any time.

Now let’s perform some more advanced operations. We will completely combine the code from the previous tutorial with the track bar. In the previous tutorial, we created a drawing board and used the Q key to switch brushes. The default is to draw a rectangle. Press Lower Q is a line drawing. Now we will change the color of the brush to complete more advanced operations. The thin drag bar can be used to adjust the thickness of the line, we still pass in its parameters:

cv2.circle(img, (x, y), thin, color, -1)

At the same time, for convenience, we also add the eraser function, which actually clears the drawing board to white.

Let's look at the code:

	view plaincopy to clipboardprint?
1. import cv2  
2. import numpy as np  
3.   
4. drawing = False  
5. mode = True  
6. ix, iy = -1, -1  

7. def nothing(x):  
8.     pass  
9.     
10.def draw_circle(event, x, y, flags, param):  
11.    r = cv2.getTrackbarPos('R', 'image')  
12.    g = cv2.getTrackbarPos('G', 'image')  
13.    b = cv2.getTrackbarPos('B', 'image')  
14.    color = (b, g, r)  
15.    s = cv2.getTrackbarPos('eraser', 'image')  
16.    if s == 1:  
17.        color = (255, 255, 255)  
18.    thin = cv2.getTrackbarPos('thin', 'image')  
19.  
20.    global ix, iy, drawing, mode  
21.    if event == cv2.EVENT_LBUTTONDOWN:  
22.        drawing = True  
23.        ix, iy = x, y  
24.    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:  
25.        if drawing:  
26.            if mode:  
27.                cv2.rectangle(img, (ix, iy), (x, y), color, -1)  
28.            else:  
29.                cv2.circle(img, (x, y), thin, color, -1)  
30.    elif event == cv2.EVENT_LBUTTONUP:  
31.        drawing == False  
32.    
33.img = np.zeros((512, 512, 3), np.uint8)  
34.img[:] = 255  
35.cv2.namedWindow('image')  
36.cv2.createTrackbar('R', 'image', 0, 255, nothing)  
37.cv2.createTrackbar('G', 'image', 0, 255, nothing)  
38.cv2.createTrackbar('B', 'image', 0, 255, nothing)   
39.cv2.createTrackbar('eraser', 'image', 0, 1, nothing)  
40.cv2.createTrackbar('thin', 'image', 1, 50, nothing)  
41.  
42.cv2.setMouseCallback('image', draw_circle)  
43.  
44.while (1):  
45.    cv2.imshow('image', img)  
46.    k = cv2.waitKey(1) & 0xFF  
47.    if k == ord('q'):  
48.        mode = not mode  
49.    elif k == 27:  
50.        break  

Experimental effect:
Insert picture description here

Isn't it pretty? Press esc to exit, press q to switch between drawing rectangles and lines. We can also simply complete a drawing operation.

So this tutorial is over here, you still have to practice more usually, not as good as practice.

Check the article summary page https://blog.csdn.net/weixin_44237705/article/details/107864965
More openvino technical information can be exchanged in the group~
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44237705/article/details/107999095