current position：Home>Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems
Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems
2022-01-30 19:58:39 【Dream eraser】
「 This is my participation 11 The fourth of the yuegengwen challenge 1 God , Check out the activity details ：2021 One last more challenge 」
The way this series is written
This series of column writing will adopt the original question and answer writing form , Quickly let you learn OpenCV My primary 、 intermediate 、 Advanced knowledge .
5. Python OpenCV Detailed description of the sliding bar in and solutions to common problems
The slider is in OpenCV The usage scenarios in related cases are very rich , Many times, it is necessary to obtain the relevant parameters with the help of the slider .
Master the slider , Just master cv2.createTrackbar And cv2.getTrackbarPos Two functions .
Prototypes of the above two functions , You can go directly through help Function lookup , This series of columns only give a brief description of the function prototype
createTrackbar(trackbarName, windowName, value, count, onChange) -> None getTrackbarPos(trackbarname, winname) -> retval Copy code
among cv2.createTrackbar The function parameters are richer ,cv2.getTrackbarPos A function is its child .
Next, through a simple case , Realize the basic application of sliding bar , Drag to change the color of a rectangle in the window .
import cv2 import numpy as np cv2.namedWindow("Trackbar_Demo", cv2.WINDOW_NORMAL) # In order to occupy the parameter position in the slider def nothing(): pass ret = np.zeros([512, 512, 3], np.uint8) # Create a slider cv2.createTrackbar("color_green", "Trackbar_Demo", 0, 255, nothing) while 1: # Get the value of the slider color_green = cv2.getTrackbarPos("color_green", "Trackbar_Demo") cv2.rectangle(ret, (100, 100), (200, 200), (0, color_green, 0), -1) cv2.imshow("Trackbar_Demo", ret) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() Copy code
If the following occurs during code writing BUG, Lack of parameter ：
TypeError: function takes exactly 5 arguments (4 given) Copy code
The BUG Express cv2.createTrackbar The last... Is missing from the function onChange Parameters , Add this parameter , The function body pointed to by the parameter can be empty .
The dynamic picture effect after running the code is as follows ：
cv2.createTrackbar Function onChange Solutions to parameter related problems
Search all Chinese materials on the Internet , You will find a knowledge point in cv2.createTrackbar Function is often ignored in the application of , So this is onChange Parameters , The official description of this parameter is as follows ：
Pointer to the function to be called every time the slider changes position. This function should be prototyped as
void Foo(int,void*);, where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only
Here is a detail to pay attention to , stay OpenCV C++ At the time of writing , There is one more parameter in this function , be called userdata , in other words C++ The prototype of this function in is as follows ：
int createTrackbar(const String& trackbarname, const String& winname, int* value, int count, TrackbarCallback onChange=0, void* userdata=0) Copy code
however Python It's integrated , The operation of two data values is completed through one parameter , So, in fact, every time we drag the slider , Can be operated accordingly .
Modify the code as follows , Space relationship , Modify only nothing Function part , Run the code and the following figure will appear ：
# The callback function of each step of the slider def nothing(x): print(" Slide bar to operate ") print(x) Copy code
I can even adjust the code logic directly , Put the rectangle drawing operation into the callback function of the scroll bar , The specific code and description are as follows ：
import cv2 import numpy as np cv2.namedWindow("Trackbar_Demo", cv2.WINDOW_NORMAL) # The callback function of each step of the slider def nothing(x): print(" Slide bar to operate ") cv2.rectangle(ret, (100, 100), (200, 200), (0, x, 0), -1) ret = np.zeros([512, 512, 3], np.uint8) # Create a slider cv2.createTrackbar("color_green", "Trackbar_Demo", 0, 255, nothing) # color_green = cv2.getTrackbarPos("color_green", "Trackbar_Demo") while True: cv2.imshow("Trackbar_Demo", ret) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() Copy code
With this logic , We can design the slider as a switch , Drag to different values , Can present different effects .
For more details , You can continue to read the relevant contents of the manual , Access address
OpenCV Split the slider and picture window
In the actual coding process , It is recommended to split the slider window and the picture window for display , It is convenient to adjust various parameters .
For example, the following manual parameter adjustment realizes the operation of binarization （ Subsequent articles will cover ）.
import cv2 import numpy as np def nothing(a): pass cv2.namedWindow("HSV",cv2.WINDOW_AUTOSIZE) cv2.createTrackbar("HUE Min", "HSV", 0, 255, nothing) cv2.createTrackbar("HUE Max", "HSV", 180, 255, nothing) cv2.createTrackbar("SAT Min", "HSV", 255, 255, nothing) cv2.createTrackbar("SAT Max", "HSV", 43, 255, nothing) cv2.createTrackbar("VALUE Min", "HSV", 255, 255, nothing) cv2.createTrackbar("VALUE Max", "HSV", 46, 255, nothing) while True: img = cv2.imread("./t1.jpg") imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h_min = cv2.getTrackbarPos("HUE Min", "HSV") h_max = cv2.getTrackbarPos("HUE Max", "HSV") s_min = cv2.getTrackbarPos("SAT Min", "HSV") s_max = cv2.getTrackbarPos("SAT Max", "HSV") v_min = cv2.getTrackbarPos("VALUE Min", "HSV") v_max = cv2.getTrackbarPos("VALUE Max", "HSV") lower = np.array([h_min, s_min, v_min]) upper = np.array([h_max, s_max, v_max]) mask = cv2.inRange(imgHsv, lower, upper) result = cv2.bitwise_and(img, img, mask=mask) mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) hStack = np.hstack([img, mask, result]) cv2.imshow('Horizontal Stacking', hStack) if cv2.waitKey(1) & 0xFF == 27: break cv2.destroyAllWindows() Copy code
After the above code runs , Will present a very convenient operation , Drag a window , The corresponding changes can be dynamically presented in another window .
There is a note when coding this place , namely cv2.namedWindow("HSV", cv2.WINDOW_AUTOSIZE) Function part , Please use cv2.WINDOW_AUTOSIZE value , If you do not use this value , It's easy to cause the slider window to be out of order , Or uneven distribution of window parameters .
Finally, another function of the slider is emphasized again , Change button . After all, OpenCV Button function does not exist in , Using a slider with a fixed value can effectively solve this problem .
The use code is as follows ：
cv2.createTrackbar(switch,'image',0,1,nothing) If this value is not used , It's easy to cause the slider window to be out of order , Or uneven distribution of window parameters . Finally, another function of the slider is emphasized again , Change button . After all, OpenCV Button function does not exist in , Using a slider with a fixed value can effectively solve this problem . The use code is as follows ： ```python cv2.createTrackbar(switch,'image',0,1,nothing) Copy code
author[Dream eraser],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
guess what you like
Python notes (11): encapsulation such as object-oriented programming
Python notes (10): concepts such as object-oriented programming
Gradient lifting method and its implementation in Python
Van * Python | simple crawling of a site course
Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
Nanny tutorial! Build VIM into an IDE (Python)
Fourier transform of Python OpenCV image processing, lesson 52
Introduction to python (III) network request and analysis
China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II（python）
- leetcode 31. Next Permutation（python）
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators