Last active
April 30, 2021 23:21
-
-
Save rinogo/d528d3b2b03d6864def1cb5117db005e to your computer and use it in GitHub Desktop.
An OpenCV utility function for displaying a set of easily-configurable trackbars and providing their results to an arbitrary callback - useful for quick prototyping and testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Usage: `python call-with-trackbars.py example.jpg` | |
import sys | |
import cv2 | |
#### Example usage #### | |
def edge_detect(p): | |
edged = cv2.Canny(p["img"], p["low"] * 15, p["high"] * 15, apertureSize = (p["aperture"] * 2) + 3) | |
cv2.imshow("Edged", edged) | |
return edged | |
def main(): | |
path = str(sys.argv[1]) | |
img = cv2.imread(path, cv2.COLOR_BGR2GRAY) | |
variables = [ | |
{ | |
"name": "low", | |
"default": 0, | |
"max": 100 | |
}, | |
{ | |
"name": "high", | |
"default": 0, | |
"max": 100 | |
}, | |
{ | |
"name": "aperture", | |
"default": 0, | |
"max": 2 | |
}, | |
] | |
call_with_trackbars({ "img": img }, variables, edge_detect) | |
#### Utility functions #### | |
#Create trackbars (sliders) for `variables` in a window named "Variables". When the trackbars change value, provide those `values`, merged with the provided `parameters`, to `callback`. | |
def call_with_trackbars(parameters, variables, callback): | |
cv2.namedWindow("Variables", cv2.WINDOW_NORMAL) | |
for variable in variables: | |
cv2.createTrackbar(variable["name"], "Variables", variable["default"], variable["max"], nothing) | |
cv2.resizeWindow("Variables", 500, 200) | |
cv2.moveWindow("Variables", 0, 500) #Doesn't work on macOS at the moment due to a bug in OpenCV (https://github.com/opencv/opencv/issues/16343) | |
values = {} | |
last_values = None | |
while(1): | |
#Break when the "Escape" key is pressed. | |
k = cv2.waitKey(1) & 0xFF | |
if k == 27: | |
break | |
for variable in variables: | |
values[variable["name"]] = cv2.getTrackbarPos(variable["name"], "Variables") | |
if(values == last_values): | |
continue | |
last_values = values.copy() | |
print(values) | |
callback({**parameters, **values}) | |
def nothing(x): | |
pass | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Released under the MIT license. Please let me know if you find this useful!