def gammaDisplay(img_path: str, rep: int): """ GUI for gamma correction :param img_path: Path to the image :param rep: grayscale(1) or RGB(2) :return: None """ img = cv2.imread(img_path, rep - 1) cv2.namedWindow('Gamma Correction') cv2.createTrackbar('Gamma', 'Gamma Correction', 1, 200, gamma) img = np.asarray(img) / 255 cv2.imshow('Gamma correction', img) k = cv2.waitKey(1) new_gamma_img = img while 1: cv2.imshow('Gamma correction', new_gamma_img) k = cv2.waitKey(1) & 0xFF if k == 27: break g = cv2.getTrackbarPos('Gamma', 'Gamma correction') print(g / 100) new_gamma_img = np.power(img, g / 100) cv2.destroyAllWindows() pass
def initialize_trackbars(initial_trackbar_values): cv.namedWindow("Adaptive Threshold") cv.resizeWindow("Adaptive Threshold", 360, 240) cv.createTrackbar('thresh_val', 'Adaptive Threshold', initial_trackbar_values[0], 1, do_nothing) cv.createTrackbar('adapt_val', 'Adaptive Threshold', initial_trackbar_values[1], 1, do_nothing) cv.createTrackbar("high_threshold", 'Adaptive Threshold', initial_trackbar_values[2], 10, do_nothing) cv.createTrackbar("block_size", 'Adaptive Threshold', initial_trackbar_values[3], 101, do_nothing) cv.createTrackbar("sub_const", 'Adaptive Threshold', initial_trackbar_values[4], 100, do_nothing)
def tune_thresholds(vid_feed, thresholds): """DOCSTRING""" # initialize window win = 'Adjustment Control Panel' cv2.namedWindow(win) # initialize variables and trackbars thresh_names = ['H_LO', 'H_HI', 'S_LO', 'S_HI', 'V_LO', 'V_HI'] blur_k_name = 'BLUR \'K\'' max_vals = [179, 179, 255, 255, 255, 255] for thresh, val, max_val in zip(thresh_names, thresholds, max_vals): cv2.createTrackbar(thresh, win, val, max_val, empty_callback) cv2.createTrackbar(blur_k_name, win, cf['blur_k']['initial'], cf['blur_k']['max'], empty_callback) cv2.setTrackbarMin(blur_k_name, win, 1) thresh_vals = None keypress = -1 while keypress == -1: __, frame = vid_feed.read() # blur frame blur_k = cv2.getTrackbarPos(blur_k_name, win) frame_blur = cv2.blur(frame, (blur_k, blur_k)) frame_hsv = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2HSV) thresh_vals = np.asarray([cv2.getTrackbarPos(name, win) for name in thresh_names]) frame_thresh = cv2.inRange(frame_hsv, thresh_vals[::2], thresh_vals[1::2]) # cv2.imshow(win_thresh, frame_thresh) cv2.imshow(win, frame_thresh) keypress = cv2.waitKey(5) cv2.destroyWindow(win) vid_feed.release() return thresh_vals, keypress
def __create_window(self) -> None: """ create a window with trackbars and a `button` to reset the trackbars """ cv.namedWindow(self.window_name, cv.WINDOW_GUI_NORMAL) # create a `button` blanco = 255 * np.ones(shape=[50, 250, 3], dtype=np.uint8) cv.putText(blanco, 'click to reset', (15, 35), cv.QT_FONT_NORMAL, 1, (0, 0, 0)) # apply the button onto the canvas cv.imshow(self.window_name, blanco) # perform an action when clicked on the `button` cv.setMouseCallback(self.window_name, self.__reset_trackbar_values) # create the trackbars to the window for bar in self.bars: cv.createTrackbar(bar.name, self.window_name, bar.min, bar.max, self.__update_trackbar_values)
def __init__( self, img, mask, classes, model, path_to_learner="./models", ): self.img_disk = self.img = img self.mask = mask self.num_classes = len(classes) self.classes = classes self.img_display = None self.key_pressed = None self.obj_selected = [] self.contours_list = [] self.model = model self.path_to_learner = path_to_learner # This will be the default window for inference cv2.namedWindow(winname="Image Objects") self.bool_segment = cv2.createTrackbar("Show Segments", "Image Objects", 0, 1, self._show_objects) cv2.setMouseCallback("Image Objects", self.mouse_events)
def demo_erosion_dilatation(img, iterations): src = img / 255 # np.max(img) # src = 1 - src # src = cv2.GaussianBlur(src, (25, 25), 0) def erosion(val): erosion_size = cv2.getTrackbarPos(title_trackbar_kernel_size, title_erosion_window) erosion_type = 0 val_type = cv2.getTrackbarPos(title_trackbar_element_type, title_erosion_window) if val_type == 0: erosion_type = cv2.MORPH_RECT elif val_type == 1: erosion_type = cv2.MORPH_CROSS elif val_type == 2: erosion_type = cv2.MORPH_ELLIPSE element = cv2.getStructuringElement( erosion_type, (2 * erosion_size + 1, 2 * erosion_size + 1), (erosion_size, erosion_size)) erosion_dst = cv2.erode(src, element, iterations=iterations) cv2.imshow(title_erosion_window, erosion_dst) def dilatation(val): dilatation_size = cv2.getTrackbarPos(title_trackbar_kernel_size, title_dilatation_window) dilatation_type = 0 val_type = cv2.getTrackbarPos(title_trackbar_element_type, title_dilatation_window) if val_type == 0: dilatation_type = cv2.MORPH_RECT elif val_type == 1: dilatation_type = cv2.MORPH_CROSS elif val_type == 2: dilatation_type = cv2.MORPH_ELLIPSE element = cv2.getStructuringElement( dilatation_type, (2 * dilatation_size + 1, 2 * dilatation_size + 1), (dilatation_size, dilatation_size)) dilatation_dst = cv2.dilate(src, element, iterations=iterations) cv2.imshow(title_dilatation_window, dilatation_dst) cv2.namedWindow(title_erosion_window) cv2.createTrackbar(title_trackbar_element_type, title_erosion_window, 0, max_elem, erosion) cv2.createTrackbar(title_trackbar_kernel_size, title_erosion_window, 0, max_kernel_size, erosion) cv2.namedWindow(title_dilatation_window) cv2.createTrackbar(title_trackbar_element_type, title_dilatation_window, 0, max_elem, dilatation) cv2.createTrackbar(title_trackbar_kernel_size, title_dilatation_window, 0, max_kernel_size, dilatation) erosion(0) dilatation(0) cv2.waitKey()
def gammaDisplay(img_path: str, rep: int): """ GUI for gamma correction Will track nar to change the gamma rate in an image The gamma will be set as: s=cr^Gamma The track bar will be [0-2] in rational numbers. :param img_path: Path to the image :param rep: grayscale(1) or RGB(2) :return: None """ # Reads the image img = cv2.imread(img_path, rep - 1) # Create the window cv2.namedWindow('Gamma correction') # Create the taskbar cv2.createTrackbar('Gamma', 'Gamma correction', 1, 200, gamma) # Normalize the img img = np.asarray(img) / 255 # Shows the image cv2.imshow('Gamma correction', img) k = cv2.waitKey(1) newim = img # Infinite loop until you press esc while 1: cv2.imshow('Gamma correction', newim) # Set a key that will stop the loop k = cv2.waitKey(1) & 0xFF if k == 27: break # Get the number from the taskbar g = cv2.getTrackbarPos('Gamma', 'Gamma correction') # Calculate the new image newim = np.power(img, g / 100) cv2.destroyAllWindows() pass
def initialize_trackbars(initial_trackbar_values): cv.namedWindow("TrackBars") cv.resizeWindow("TrackBars", 360, 240) cv.createTrackbar('min', 'TrackBars', initial_trackbar_values[0], 255, do_nothing) cv.createTrackbar('max', 'TrackBars', initial_trackbar_values[1], 255, do_nothing) cv.createTrackbar("apertureSize", 'TrackBars', initial_trackbar_values[2], 7, do_nothing)
def adjust_circle(image, circle): """Manually adjust a circle on an image. Takes an input image and circle(center, radius) and shows a blown up region centered around the circle. Allows the user to adjust the circle using trackbars. Waits for keypress to finish. Returns adjusted circle and keypress.""" # initialize window and trackbars win = 'Adjust Target Circle' cv2.namedWindow(win) cv2.resizeWindow(win, 200, 200) # initialize variables roi, roi_origin = get_circle_roi(image, circle) circle_local = np.copy(circle) circle_local[0] = circle[0] - np.flipud(roi_origin) # scale image to be bigger and allow for easier adjustment scale = cf['roi']['ADJUST_SCALE'] roi = scale_image(roi, scale) circle_local = np.multiply(circle_local, scale) img_circ = np.copy(roi) # Set max radius of circle such that the max diameter is the length # of the region of interest max_radius = roi.shape[0] // 2 # initialize trackbars cv2.createTrackbar('x', win, circle_local[0][0], roi.shape[1], empty_callback) cv2.createTrackbar('y', win, circle_local[0][1], roi.shape[0], empty_callback) cv2.createTrackbar('r', win, circle_local[1], max_radius, empty_callback) keypress = -1 while keypress == -1: cv2.circle(img_circ, (cv2.getTrackbarPos('x', win), cv2.getTrackbarPos('y', win)), cv2.getTrackbarPos('r', win), (0, 0, 0), 1) cv2.imshow(win, img_circ) img_circ = np.copy(roi) keypress = cv2.waitKey(5) adj_circle = ((cv2.getTrackbarPos('x', win) // scale + roi_origin[1], cv2.getTrackbarPos('y', win) // scale + roi_origin[0]), cv2.getTrackbarPos('r', win) // scale) cv2.destroyWindow(win) return adj_circle, keypress
def _create_share_overlap_window(share_1, share_2): global share_1_global, share_2_global, denoise, fix_proportion, offset share_1_global = share_1 share_2_global = share_2 cv2.namedWindow("Visual cryptography") cv2.createTrackbar("Overlap", "Visual cryptography", 0, share_1.shape[0], _callback_1) cv2.createTrackbar("Denoise", "Visual cryptography", 0, 1, _callback_2) cv2.createTrackbar("Fix proportions", "Visual cryptography", 0, 1, _callback_3) _show_overlapped_shares() cv2.waitKey() cv2.destroyAllWindows() denoise = False fix_proportion = False offset = 0
def calibrate_params(filename="planszafullborder.jpg"): WINDOW_NAME = "Config" cv2.namedWindow(WINDOW_NAME) cv2.createTrackbar('param1', WINDOW_NAME, 10, 255, nothing) cv2.createTrackbar('param2', WINDOW_NAME, 10, 255, nothing) switch = ' \n1 : SAVE Config' cv2.createTrackbar(switch, WINDOW_NAME, 0, 1, nothing) img = load_image(filename) # img = resize(20, img) output = img.copy while (1): param1 = cv2.getTrackbarPos('param1', WINDOW_NAME) param2 = cv2.getTrackbarPos('param2', WINDOW_NAME) s = cv2.getTrackbarPos(switch, WINDOW_NAME) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray_blurred = cv2.medianBlur(gray, 5) detected_circles = cv2.HoughCircles(gray_blurred, cv2.HOUGH_GRADIENT, 1, 30, param1=param1, param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8)) if detected_circles is not None: output = img.copy() detected_circles = np.uint16(np.around(detected_circles)) for (x, y, r) in detected_circles[0, :]: cv2.circle(output, (x, y), r, (0, 255, 0), 4) cv2.imshow(WINDOW_NAME, output) k = cv2.waitKey(1) & 0xFF if k == 27: break if s == 1: d = dict() d["param1"] = param1 d["param2"] = param2 json.dump(d, open(save_configs("config.txt"), 'w')) break cv2.destroyAllWindows()
ver = np.vstack(hor) else: for x in range(0, rows): if imgArray[x].shape[:2] == imgArray[0].shape[:2]: imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale) else: imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale) if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR) hor= np.hstack(imgArray) ver = hor return ver cv2.namedWindow("TrackBars") #craeting a trackbar to find optimal values of hue , sat and val cv2.resizeWindow("TrackBars", 640,240) cv2.createTrackbar("Hue Min", "TrackBars",0,179,empty) cv2.createTrackbar("Hue Max", "TrackBars",179,179,empty) cv2.createTrackbar("Sat Min", "TrackBars",0,255,empty) cv2.createTrackbar("Sat Max", "TrackBars",255,255,empty) cv2.createTrackbar("Val Min", "TrackBars",0,255,empty) cv2.createTrackbar("Val Max", "TrackBars",255,255,empty) livecap = cv2.VideoCapture(0) livecap.set(3, 600) # 3 represents height here livecap.set(4, 400) # 4 represents width here livecap.set(10, 1000) # 10 represents brightnes
import cv2.cv2 as cv def some_func(x): pass cv.namedWindow("Canny edge detection") img = cv.imread("imgs/messi5.jpg", 0) cv.createTrackbar("th1", "Canny edge detection", 0, 255, some_func) cv.createTrackbar("th2", "Canny edge detection", 0, 255, some_func) while True: th1 = cv.getTrackbarPos("th1", "Canny edge detection") th2 = cv.getTrackbarPos("th2", "Canny edge detection") canny = cv.Canny(img, th1, th2) cv.imshow("Canny edge detection", canny) if cv.waitKey(1) == ord(' '): break canny = cv.Canny(img, th1, th2) cv.destroyAllWindows()
update(newpoint, points_list_2, 2) print(Maxpoint_1) print(Maxpoint_2) # 转化为整数点以作直线 line_point_1_a = (int(Maxpoint_1[0][0]), int(Maxpoint_1[0][1])) line_point_1_b = (int(Maxpoint_1[1][0]), int(Maxpoint_1[1][1])) line_point_2_a = (int(Maxpoint_2[0][0]), int(Maxpoint_2[0][1])) line_point_2_b = (int(Maxpoint_2[1][0]), int(Maxpoint_2[1][1])) # 画出直线 cv.line(img, line_point_1_a, line_point_1_b, (0, 0, 255), 2) cv.line(img, line_point_2_a, line_point_2_b, (0, 255, 0), 2) cv.namedWindow('template') cv.createTrackbar('Canny_thresh1', 'template', 41, 255, nothing) cv.createTrackbar('Canny_thresh2', 'template', 237, 255, nothing) # cv.createTrackbar('thresh', 'template', 100, 255, nothing) # cv.createTrackbar('minLine', 'template', 5, 50, nothing) # cv.createTrackbar('maxlineGap', 'template', 1, 50, nothing) while True: lower = cv.getTrackbarPos('Canny_thresh1', 'template') upper = cv.getTrackbarPos('Canny_thresh2', 'template') edges = cv.Canny(img_gray, lower, upper, apertureSize=3) # thresh = cv.getTrackbarPos('thresh', 'template') # minLineLength = cv.getTrackbarPos('minLine', 'template') # maxLineGap = cv.getTrackbarPos('maxlineGap', 'template') thresh = 100 minLineLength = 5 maxLineGap = 1
from cv2 import cv2 import numpy as np def nothing(x): print(x) img = np.zeros((300, 512, 3), np.uint8) cv2.namedWindow("Image") cv2.createTrackbar('B', "Image", 0, 255, nothing) cv2.createTrackbar('G', "Image", 0, 255, nothing) cv2.createTrackbar('R', "Image", 0, 255, nothing) while(1): cv2.imshow("Image", img) k = cv2.waitKey(1) & 0xFF if k==27: break cv2.destroyAllWindows()
import cv2.cv2 as cv import numpy as np # Create a black image, a window img = np.zeros((300, 512, 3), np.uint8) #naming window(title) cv.namedWindow("image") def some_func(x): print(x) switch = '0 : OFF\n 1 : ON' cv.createTrackbar('B', 'image', 0, 255, some_func) cv.createTrackbar('G', 'image', 0, 255, some_func) cv.createTrackbar('R', 'image', 0, 255, some_func) cv.createTrackbar(switch, 'image', 0, 1, some_func) while True: cv.imshow("image", img) k = cv.waitKey(1) if k == 27: break b = cv.getTrackbarPos('B', 'image') g = cv.getTrackbarPos('G', 'image') r = cv.getTrackbarPos('R', 'image') s = cv.getTrackbarPos(switch, 'image') if s == 0:
import numpy as np def onchange_fxn(x): # x is the value of trackbar print(x) #img = np.zeros((400,600,3) , np.uint8) cv2.namedWindow( 'Trackbar_Window') # Creating a window with name as "Trackbar_Window" # Syntax of creating trackbar # cv2.createTrackbar( trackbar_name, window_name, min_value, max_value, function_to_be_called) cv2.createTrackbar( 'Blue_Channel', 'Trackbar_Window', 0, 255, onchange_fxn) # Trackbar to change the values for Blue channel cv2.createTrackbar( 'Green_Channel', 'Trackbar_Window', 0, 255, onchange_fxn) # Trackbar to change the values for Green channel cv2.createTrackbar( 'Red_Channel', 'Trackbar_Window', 0, 255, onchange_fxn) # Trackbar to change the values for Red channel # Creating a switch switch_name = "Switch-\n 0: ON \n 1: OFF " cv2.createTrackbar(switch_name, 'Trackbar_Window', 0, 1, onchange_fxn) while (1): # Whenever using while loop always place image inside the loop img = np.zeros((400, 600, 3), np.uint8) # Getting the positions of the Trackbars
def main(): global short while 1: k = clahe_tune(short) if cv2.waitKey(1) & 0xFF == ord("q"): cv2.imwrite("Final.jpg", k) break if __name__ == "__main__": cv2.namedWindow("track") cv2.createTrackbar("clip", "track", 18, 100, nothing) cv2.createTrackbar("tg", "track", 20, 200, nothing) cv2.createTrackbar("kernel", "track", 3, 200, nothing) cv2.createTrackbar("t", "track", 5, 200, nothing) dataset_no = 2 short = cv2.imread( os.path.join( current_dir, os.path.join("dataset/" + str(dataset_no), str(dataset_no) + ".JPG"), )) long = cv2.imread( os.path.join( current_dir,
# Detectar objeto pela cor from cv2 import cv2 import numpy as np cap = cv2.VideoCapture(0) def nothing(x): pass cv2.namedWindow("Tracking") cv2.createTrackbar("LH", "Tracking", 0, 255, nothing) cv2.createTrackbar("LS", "Tracking", 0, 255, nothing) cv2.createTrackbar("LV", "Tracking", 0, 255, nothing) cv2.createTrackbar("UH", "Tracking", 255, 255, nothing) cv2.createTrackbar("US", "Tracking", 255, 255, nothing) cv2.createTrackbar("UV", "Tracking", 255, 255, nothing) while True: ret, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Pega a posição e o valor de cada trackbar l_h = cv2.getTrackbarPos("LH", "Tracking") l_s = cv2.getTrackbarPos("LS", "Tracking") l_v = cv2.getTrackbarPos("LV", "Tracking") u_h = cv2.getTrackbarPos("UH", "Tracking")
def trackbarwindow(self): def empty(a): pass cv2.namedWindow(self.winname) cv2.resizeWindow(self.winname, 640, 240) cv2.createTrackbar(self.trackbar_name[0], self.winname, 0, 179, empty) cv2.createTrackbar(self.trackbar_name[1], self.winname, 88, 179, empty) cv2.createTrackbar(self.trackbar_name[2], self.winname, 41, 255, empty) cv2.createTrackbar(self.trackbar_name[3], self.winname, 255, 255, empty) cv2.createTrackbar(self.trackbar_name[4], self.winname, 114, 255, empty) cv2.createTrackbar(self.trackbar_name[5], self.winname, 255, 255, empty)
import numpy as np from cv2 import cv2 from collections import deque #default called trackbar function def setValues(x): print("") # Creating the trackbars needed for adjusting the marker colour cv2.namedWindow("Color detectors") cv2.createTrackbar("Upper Hue", "Color detectors", 153, 255,setValues) cv2.createTrackbar("Upper Saturation", "Color detectors", 255, 255,setValues) cv2.createTrackbar("Upper Value", "Color detectors", 255, 255,setValues) cv2.createTrackbar("Lower Hue", "Color detectors", 64, 150,setValues) cv2.createTrackbar("Lower Saturation", "Color detectors", 171, 255,setValues) cv2.createTrackbar("Lower Value", "Color detectors", 77, 255,setValues) # Giving different arrays to handle colour points of different colour bpoints = [deque(maxlen=1024)] gpoints = [deque(maxlen=1024)] rpoints = [deque(maxlen=1024)] ypoints = [deque(maxlen=1024)] # These indexes will be used to mark the points in particular arrays of specific colour blue_index = 0 green_index = 0 red_index = 0 yellow_index = 0
def analyseVideoStream(mode, pathToFile): window_name = "" cap = "" if mode == 1: window_name = "Webcam" cap = cv.VideoCapture(0) elif mode == 2: window_name = "Video" cap = cv.VideoCapture(pathToFile) trackbar_name = "Size" cv.namedWindow(window_name) cv.setMouseCallback(window_name, selectROI) cv.createTrackbar(trackbar_name, window_name, 10, 50, nothing) window_top_left_pt = (0, 0) window_bottom_right_pt = (0, 0) while (True): ret, frame = cap.read() if ret == False: break output = frame size = cv.getTrackbarPos(trackbar_name, window_name) mouse_rectangle_dimension = size window_top_left_pt = (mouse_position[0] - mouse_rectangle_dimension, mouse_position[1] + mouse_rectangle_dimension) window_bottom_right_pt = (mouse_position[0] + mouse_rectangle_dimension, mouse_position[1] - mouse_rectangle_dimension) cursorROI = output[window_bottom_right_pt[1]:window_top_left_pt[1], window_top_left_pt[0]:window_bottom_right_pt[0]] height, width, _ = cursorROI.shape if height > 0 and width > 0: cv.imshow("Cursor ROI", cursorROI) cv.rectangle(output, window_top_left_pt, window_bottom_right_pt, (0, 0, 255), 1) if selecting: window_color = calculateColor(cursorROI) height_o, width_o, _ = output.shape x_pos = 0 y_pos = 0 if window_bottom_right_pt[1] + 25 < height_o * 0.8: y_pos = window_top_left_pt[1] + 25 else: y_pos = window_top_left_pt[1] - 25 - size if window_bottom_right_pt[0] + 25 < width_o * 0.9: x_pos = window_top_left_pt[0] else: x_pos = window_top_left_pt[0] - 100 cv.putText(output, window_color, (x_pos, y_pos), cv.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2) cv.imshow(window_name, output) k = cv.waitKey(1) & 0xFF if k == ord('q'): break cap.release() cv.destroyAllWindows()
def analyseImage(pathToImage): window_name = "Image" trackbar_name = "Size" img = cv.imread(pathToImage, cv.IMREAD_COLOR) clone = img.copy() cv.namedWindow(window_name) cv.setMouseCallback(window_name, selectROI) cv.createTrackbar(trackbar_name, window_name, 10, 50, nothing) window_top_left_pt = (0, 0) window_bottom_right_pt = (0, 0) while (True): img = clone.copy() size = cv.getTrackbarPos(trackbar_name, window_name) mouse_rectangle_dimension = size window_top_left_pt = (mouse_position[0] - mouse_rectangle_dimension, mouse_position[1] + mouse_rectangle_dimension) window_bottom_right_pt = (mouse_position[0] + mouse_rectangle_dimension, mouse_position[1] - mouse_rectangle_dimension) cursorROI = img[window_bottom_right_pt[1]:window_top_left_pt[1], window_top_left_pt[0]:window_bottom_right_pt[0]] cv.rectangle(img, window_top_left_pt, window_bottom_right_pt, (0, 0, 255), 1) if selecting: window_color = calculateColor(cursorROI) height_o, width_o, _ = img.shape x_pos = 0 y_pos = 0 if window_bottom_right_pt[1] + 25 < height_o * 0.8: y_pos = window_top_left_pt[1] + 25 else: y_pos = window_top_left_pt[1] - 25 - size if window_bottom_right_pt[0] + 25 < width_o * 0.9: x_pos = window_top_left_pt[0] else: x_pos = window_top_left_pt[0] - 100 cv.putText(img, window_color, (x_pos, y_pos), cv.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2) cv.imshow(window_name, img) key = cv.waitKey(1) & 0xFF if key == ord("q"): break cv.destroyAllWindows()
from cv2 import cv2 import numpy as np def nothing(x): pass img = np.zeros((512, 512, 3), np.uint8) cv2.namedWindow('image') #window name #create trackbar cv2.createTrackbar('B', 'image', 0, 255, nothing) cv2.createTrackbar('G', 'image', 0, 255, nothing) cv2.createTrackbar('R', 'image', 0, 255, nothing) #switch switch = '0:OFF\n 1:ON' cv2.createTrackbar(switch, 'image', 0, 1, nothing) while (1): cv2.imshow('image', img) k = cv2.waitKey(1) & 0xFF if k == 27: break # get current positions of four trackbars r = cv2.getTrackbarPos('R', 'image') g = cv2.getTrackbarPos('G', 'image') b = cv2.getTrackbarPos('B', 'image') s = cv2.getTrackbarPos(switch, 'image') if s == 0: img[:] = 0 else:
from cv2 import cv2 import numpy as np img = cv2.imread("Resources/lambo.png") imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) window = cv2.namedWindow("Trackbars") cv2.resizeWindow("Trackbars", 512, 512) cv2.createTrackbar("Hue Min", "Trackbars", 0, 179, lambda x: x) cv2.createTrackbar("Hue Max", "Trackbars", 24, 179, lambda x: x) cv2.createTrackbar("Sat Min", "Trackbars", 88, 255, lambda x: x) cv2.createTrackbar("Sat Max", "Trackbars", 255, 255, lambda x: x) cv2.createTrackbar("Val Min", "Trackbars", 137, 255, lambda x: x) cv2.createTrackbar("Val Max", "Trackbars", 255, 255, lambda x: x) while True: mins = np.array([ cv2.getTrackbarPos("Hue Min", "Trackbars"), cv2.getTrackbarPos("Sat Min", "Trackbars"), cv2.getTrackbarPos("Val Min", "Trackbars") ], dtype=np.uint8) maxes = np.array([ cv2.getTrackbarPos("Hue Max", "Trackbars"), cv2.getTrackbarPos("Sat Max", "Trackbars"), cv2.getTrackbarPos("Val Max", "Trackbars") ], dtype=np.uint8) mask = cv2.inRange(imgHSV, mins, maxes) result = cv2.bitwise_and(img, img, mask=mask)
if k == 27: cv.destroyAllWindows() def nothing(x): pass img = cv.imread('timg.jpg', cv.IMREAD_GRAYSCALE) # v1 = cv.Canny(img, 80, 150) # v2 = cv.Canny(img, 50, 100) # res = np.hstack((v1, v2)) # cv_show('res', res) cv.namedWindow('window') cv.createTrackbar('bar_low', 'window', 0, 255, nothing) cv.createTrackbar('bar_up', 'window', 0, 255, nothing) while (True): low = cv.getTrackbarPos('bar_low', 'window') up=cv.getTrackbarPos('bar_up','window') res = cv.Canny(img, low, up) cv.imshow('window', res) key = cv.waitKey(10) if key == 27: break
# Define all the global variables heightImg = 640 widthImg = 480 Image_Resolution_height = 640 Image_Resolution_width = 480 # For Photo from live Webcam feed #img_counter=utilities.webcamfeed(heightImg,widthImg,Image_Resolution_height,Image_Resolution_width) img_counter = 2 #For Live Webcam feed, uncomment next line #if webCamFeed:success, img = cap.read() #else: # Reading the Image # Filepath of Image pathImage = "opencv_frame_{}.png".format(img_counter - 1) img = cv2.imread(pathImage) heightImg, widthImg, _ = img.shape # Trackbars for Threshold 1 and 2 cv2.namedWindow("Threshold Parameters") cv2.resizeWindow("Threshold Parameters", 400, 600) cv2.createTrackbar("Threshold 1", "Threshold Parameters", 60, 255, utilities.nothing) cv2.createTrackbar("Threshold 2", "Threshold Parameters", 60, 255, utilities.nothing) Warped_Img = utilities.process(img, heightImg, widthImg) print(1) utilities.adaptive_thresholding(Warped_Img, heightImg, widthImg)
img = black_img = np.zeros((768, 1366, 3), np.uint8) # full black image cv2.namedWindow('image') def change_color(x): if cv2.getTrackbarPos(switch, 'image') == 0: return img[:] = [ cv2.getTrackbarPos('B', 'image'), cv2.getTrackbarPos('G', 'image'), cv2.getTrackbarPos('R', 'image') ] return switch = '0 : OFF \n1 : ON' cv2.createTrackbar(switch, 'image', 0, 1, change_color) cv2.createTrackbar('B', 'image', 0, 255, change_color) cv2.createTrackbar('G', 'image', 0, 255, change_color) cv2.createTrackbar('R', 'image', 0, 255, change_color) while (1): cv2.imshow('image', black_img) k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyWindow('image')
def stereo_bm(self): Left_Stereo_Map = (config.left_map1, config.left_map2) Right_Stereo_Map = (config.right_map1, config.right_map2) cv.namedWindow("Test Two Camera") cv.namedWindow('depth') cv.createTrackbar("numDisparities", "depth", 9, 100, lambda x: None) cv.createTrackbar("filterCap", "depth", 62, 63, lambda x: None) cv.createTrackbar("filterSize", "depth", 255, 255, lambda x: None) cv.createTrackbar("SADWindowSize", "depth", 0, 255, lambda x: None) leftCam = cv.VideoCapture(self.left_camera_id + cv.CAP_DSHOW) rightCam = cv.VideoCapture(self.right_camera_id + cv.CAP_DSHOW) leftCam.set(cv.CAP_PROP_FRAME_HEIGHT, self.frameHeight) leftCam.set(cv.CAP_PROP_FRAME_WIDTH, self.frameWidth) rightCam.set(cv.CAP_PROP_FRAME_HEIGHT, self.frameHeight) rightCam.set(cv.CAP_PROP_FRAME_WIDTH, self.frameWidth) if not (leftCam.isOpened() and rightCam.isOpened()): exit(1) while True: # Start Reading Camera images retvalOfRight, rightFrame = rightCam.read() retvalOfLeft, leftFrame = leftCam.read() # ret, frame = capture.read() if not (retvalOfRight and retvalOfLeft): print("read fail") break key = cv.waitKey(1) twoFrame = cv.hconcat([rightFrame, leftFrame]) cv.imshow("Test Two Camera", twoFrame) if key & 0xFF == ord('q'): print("結束") break # elif key & 0xFF == ord('s'): elif 1 == 1: frameL = leftFrame frameR = rightFrame else: continue cv.imshow("left", frameL) cv.imshow("right", frameR) Left_nice = cv.remap(frameL, Left_Stereo_Map[0], Left_Stereo_Map[1], cv.INTER_LANCZOS4, cv.BORDER_CONSTANT, 0) Right_nice = cv.remap(frameR, Right_Stereo_Map[0], Right_Stereo_Map[1], cv.INTER_LANCZOS4, cv.BORDER_CONSTANT, 0) grayR = cv.cvtColor(Right_nice, cv.COLOR_BGR2GRAY) grayL = cv.cvtColor(Left_nice, cv.COLOR_BGR2GRAY) numDisparities = cv.getTrackbarPos("numDisparities", "depth") filterCap = cv.getTrackbarPos("filterCap", "depth") filterSize = cv.getTrackbarPos("filterSize", "depth") if filterSize % 2 == 0: filterSize += 1 if filterSize < 5: filterSize = 5 if filterCap < 1: filterCap = 1 SADWindowSize = cv.getTrackbarPos("SADWindowSize", "depth") if SADWindowSize % 2 == 0: SADWindowSize += 1 if SADWindowSize < 5: SADWindowSize = 5 stereo = cv.StereoBM_create(numDisparities=16 * numDisparities, blockSize=SADWindowSize) stereo.setPreFilterCap(filterCap) stereo.setPreFilterSize(filterSize) disparity = stereo.compute(grayL, grayR) disparity.astype(np.float32) / 16 disp = cv.normalize(disparity, disparity, alpha=255, beta=1, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8UC1) cv.imshow("depth", disp)
else: imgArray[x] = cv2.resize( imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale) if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR) hor = np.hstack(imgArray) ver = hor return ver # Define Trackbars cv2.namedWindow('TrackBars') cv2.resizeWindow('TrackBars', 640, 240) cv2.createTrackbar('Hue Min', 'TrackBars', 0, 179, empty_fn) cv2.createTrackbar('Hue Max', 'TrackBars', 19, 179, empty_fn) cv2.createTrackbar('Sat Min', 'TrackBars', 110, 255, empty_fn) cv2.createTrackbar('Sat Max', 'TrackBars', 240, 255, empty_fn) cv2.createTrackbar('Val Min', 'TrackBars', 153, 255, empty_fn) cv2.createTrackbar('Val Max', 'TrackBars', 255, 255, empty_fn) while True: # Read image file from path path = 'Resources/lambo.png' img = cv2.imread(path) # convert image to HSV imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Get the value from the trackbar