def simple_trackbar(img, window_name='trackbar'): # Generate trackbar Window Name trackbar_name = window_name # Make Window and Trackbar cv2.namedWindow(window_name) cv2.createTrackbar(trackbar_name, window_name, 0, 255, nothing) # Allocate destination image threshold = np.zeros(img.shape, np.uint8) # Loop for get trackbar pos and process it while True: # Get position in trackbar trackbar_pos = cv2.getTrackbarPos(trackbar_name, window_name) # Apply threshold cv2.threshold(img, trackbar_pos, 255, cv2.THRESH_BINARY, threshold) # Show in window cv2.imshow(window_name, threshold) # If you press "ESC", it will return value ch = cv2.waitKey(5) if ch == 27: break cv2.destroyAllWindows() return threshold
def main(): def nothing(x): pass if len(sys.argv) > 1: path = sys.argv[1] base_dir = os.getcwd() directory = os.path.join(base_dir, path) if not os.path.exists(directory): print "Invalid Path - Directory does not exist" exit() img_dirs = [ image for image in os.listdir(directory) if os.path.splitext(image)[1][1:] in ['png', 'jpg', 'bmp'] ] cv2.namedWindow('original') cv2.createTrackbar('Playback Speed:', 'original', 100, 200, nothing) counter = 0 for img in sorted(img_dirs): frame = cv2.imread(os.path.join(directory, img)) counter += 1 cv2.putText(frame, "frame #: " + str(counter), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.CV_AA) cv2.putText(frame, "frame path: " + img, (50, 70), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.CV_AA) cv2.imshow('original', frame) speed = cv2.getTrackbarPos('Playback Speed:', 'original') # 2000 * 100% = 20 fps, 8000 * 100% = 5 fps cv2.waitKey(int(8000 / (speed + 1)))
def play(self, draw=False): idx = 0 cv2.namedWindow('Playback') cv2.createTrackbar('Ts', 'Playback', self.Ts, 200, lambda x: x) paused = True valid = True while valid: delay = cv2.getTrackbarPos('Ts', 'Playback') if delay == 0: delay = 1 if not paused: valid,frame = self.mov.read() if not valid: break tstr = "%0.3f"%(self.t[idx]-self.t[0]) frame = frame.astype(np.uint8) cv2.putText(frame, tstr, (0,frame.shape[0]-3), cv2.FONT_HERSHEY_SIMPLEX, 1., (255,255,255)) if draw and self.tracking!=None and self.contours[idx].shape[0]>1: cv2.drawContours(frame, self.contours[idx], -1, (200,200,200), thickness=3) cv2.imshow('Playback', frame) idx += 1 k = cv2.waitKey(delay) if k == ord('p'): paused = not paused elif k == ord('q'): break cv2.destroyAllWindows()
def goLiveT(): cap = cv2.VideoCapture(0) cv2.namedWindow('image') # create trackbars for color change cv2.createTrackbar('Thres','image',0,255,nothing) # create switch for ON/OFF functionality switch = '0 : OFF \n1 : ON' cv2.createTrackbar(switch, 'image',0,1,nothing) while (1): _, imgOriginal = cap.read() cv2.imshow('imgOriginal',imgOriginal) filteredImage = rb.clearImage(imgOriginal) # get current positions of four trackbars binValue = cv2.getTrackbarPos('Thres','image') s = cv2.getTrackbarPos(switch,'image') k = cv2.waitKey(1) & 0xFF if k == 27: break if s == 0: pass else: thresImage = rb.doThresHold(filteredImage,binValue) cv2.imshow('img', thresImage) cv2.destroyAllWindows()
def _detect_edges(self, image, vary=False, plot=False): """ :param image: image file name (str) :param vary: turn tunable plotting on :param plot: turn plotting on :return: detected edges with variable filters """ self.image = self._load_image(image) if vary: def nothing(x): pass cv2.namedWindow('image') cv2.createTrackbar('th1', 'image', 0, 255, nothing) cv2.createTrackbar('th2', 'image', 0, 255, nothing) while True: th1 = cv2.getTrackbarPos('th1', 'image') th2 = cv2.getTrackbarPos('th2', 'image') edges = cv2.Canny(self.image, th1, th2) cv2.imshow('image', edges) k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows() edges = cv2.Canny(self.image, 255, 255) if plot: cv2.namedWindow('image') cv2.imshow('image', edges) cv2.waitKey(5000) cv2.destroyAllWindows() return edges
def test_vein_based_features(argv): for fimg in argv[1:]: cv2.namedWindow("Veins") #cv2.createTrackbar("Threshold", "Veins", 0, 255, trckbr_cb) cv2.createTrackbar("Kernel", "Veins", 1, 8, trckbr_cb) ori = cv2.imread(fimg, cv2.IMREAD_COLOR) while(1): img = ori.copy() gsc = ori.copy() gsc = bgr2gray(gsc) cnt = get_contours(gsc) kr = cv2.getTrackbarPos("Kernel", "Veins") k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kr,kr)) opening = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, k) #thld = cv2.getTrackbarPos("Threshold", "Veins") ret, img = cv2.threshold(opening, 15, 255, cv2.THRESH_BINARY) #opening = cv2.Laplacian(img, cv2.CV_8U) #cv2.imshow("Veins", opening) img = bgr2gray(img) cv2.imshow("Veins", img) k = cv2.waitKey(1) & 0xFF if k == 27: break
def get_hls_range(img, winname=None): if winname is None: winname = 'Choose HLS bounds' h, w, _ = img.shape f = 720.0 / h img_720p = cv2.resize(img, dsize=None, fx=f, fy=f) def on_trackbar_changed(x): lowerb = tuple( cv2.getTrackbarPos(ch + '_min', winname) for ch in 'HLS') upperb = tuple( cv2.getTrackbarPos(ch + '_max', winname) for ch in 'HLS') out = img_util.apply_mask_hls(img_720p, lowerb, upperb) cv2.imshow(winname, out) cv2.imshow(winname, img_720p) for ch in 'HLS': cv2.createTrackbar(ch + '_min', winname, 0, 255, on_trackbar_changed) cv2.createTrackbar(ch + '_max', winname, 255, 255, on_trackbar_changed) while True: cv2.waitKey() lowerb = tuple( cv2.getTrackbarPos(ch + '_min', winname) for ch in 'HLS') upperb = tuple( cv2.getTrackbarPos(ch + '_max', winname) for ch in 'HLS') cv2.destroyWindow(winname) return lowerb, upperb
def loop(processimg): if not use_webcam: ctx = freenect.init() dev = freenect.open_device(ctx, 0) freenect.set_tilt_degs(dev, 10) freenect.close_device(dev) cv2.namedWindow('processing') for k, v in params.iteritems(): cv2.createTrackbar(k, 'processing', v, 255, onchange(k)) runonce = True while runonce: #runonce = False if imgpath != "": img = cv2.imread(imgpath) else: img = getimg() cv2.imshow('processing', cv2.resize(processimg(img), (width, height))) char = cv2.waitKey(10) if char == 27: break elif char == ord('p'): for k, v in params.iteritems(): print "%s: %d" % (k, v) #freenect.set_tilt_degs(dev, pid) cv2.destroyAllWindows()
def apply_butterworth_filter(self): """ Apply Butterworth low pass filter. The code is derived from Paragraph 4.8.2, Butterworth Lowpass Filters, "Digital image Processing (3rd edition)" by R.C. Gonzalez. """ max_ksize = max(self.img.shape[0], self.img.shape[1]) self.dft4img = self.get_dft(self.img, showdft=True) cv2.imshow(self.test_winname, self.img) cv2.imshow(self.ctrl_panel_winname, np.zeros((100, 600), np.uint8)) cv2.createTrackbar( "stopband**2", self.ctrl_panel_winname, 3, (max_ksize - 1) / 2, self.update_butterworth_win) self.update_butterworth_win() print "Reducing high frequency noise, Press a to accept" while True: ch = cv2.waitKey() if ch == 27: break if ch == 97: self.img = self.tmp plt.imshow(self.img) plt.show() break cv2.destroyAllWindows()
def tb(self, use_avg=False, minVal=0, maxVal=160, ratio=3, kernel_size=3): #trackbar to pick canny min/max if not use_avg: if self.My_Covar == None: self.covar_z() class local: array = self.My_Covar if use_avg: class local: array = self.My_Avg def cannythresh(minVal): array = local.array array *= 255/array.max() array = np.array(array,np.uint8) det_edges = cv2.Canny(array,minVal,minVal*ratio,apertureSize = kernel_size) dst = cv2.bitwise_and(array, array, mask = det_edges) print(minVal, minVal*ratio) cv2.imshow('Image', dst) while True: cv2.namedWindow('Image', cv2.WINDOW_NORMAL) minVal = 0 cv2.createTrackbar('Min Threshold:', 'Image', minVal, maxVal, cannythresh) cannythresh(0) if cv2.waitKey(1) & 0xFF == ord(' '): #Press space to exit image. break cv2.destroyAllWindows()
def thresholding(x): global thres, value, maxValue, img, tipo imgO = img if (x == 0): thres = None filtro = img value = 0 maxValue = 255 cv2.createTrackbar('Value', windowTitle, value, maxValue, fValue) cv2.createTrackbar('MaxValue', windowTitle, maxValue, maxValue, fMaxValue) elif (x == 1): thres = cv2.THRESH_BINARY+cv2.THRESH_OTSU elif (x==2): thres = cv2.THRESH_BINARY+cv2.THRESH_OTSU img = cv2.GaussianBlur(img,(5,5),0) if (x != 0): ret, filtro = cv2.threshold(img,value, maxValue, thres) tipo = x img = imgO blobImg = Image(filtro) invImg = blobImg.invert() blobImg = blobImg.rotate90() invImg = blobImg.invert() blobs = invImg.findBlobs() for blob in blobs: #print blob.coordinates() invImg.dl().circle(blob.coordinates(), 3, Color.RED, filled = True) blobImg.addDrawingLayer(invImg.dl()) blobs.show(color=Color.GREEN,width=1) cv2.imshow(windowTitle, filtro)
def show(self, verbose=False): # create window, event callbacks cv2.namedWindow(self.name) cv2.setMouseCallback(self.name, self._onclick) cv2.createTrackbar('Tolerance', self.name, self._tolerance[0], 255, self._onchange) self.verbose = verbose if verbose: print('Click anywhere to select a region of similar colors.') print('Move the slider to include a wider range of colors.\n') print(('Press [m] to switch between displaying the selection, ' 'mask, or applied mask')) print('Press [p] to print color statistics of current selection') print('Press [s] to save the currently displayed image') print('Press [q] or [esc] to close the window') print('------------------------------------------------------------\n') # display the image and wait for a keypress or trackbar change cv2.imshow(self.name, self._image) while(True): k = cv2.waitKey() & 0xFF if k == ord('q') or k == 27: # 27 is [esc] self._close() break elif k == ord('m'): self._flip_displays() elif k == ord('p'): self._print_stats() elif k == ord('s'): self._save()
def main(): if len(sys.argv) != 2: print "Usage : python display_image.py <image_file>" else: global img, img_hsv img = cv2.imread(sys.argv[1], cv2.CV_LOAD_IMAGE_COLOR) if (img == None): print "Could not open or find the image" else: img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) img_thresh = cv2.inRange(img, COLOR_MIN, COLOR_MAX) cv2.createTrackbar('Hue:','Display Window', 0, 255, changed(0)) cv2.createTrackbar('Saturation:','Display Window', 0, 255, changed(1)) cv2.createTrackbar('Value:','Display Window', 0, 255, changed(2)) cv2.createTrackbar('Blob', 'Display Window', 0, 50000, changedBlobSize) cv2.createTrackbar('Range:', 'Display Window', 0, 255, changedRange) cv2.imshow('Display Window',img) print "size of image: ", img.shape cv2.waitKey(0) cv2.destroyAllWindows()
def __init__(self, min_range=672, max_range=2608): self.running = True img = np.zeros((1,1000), np.uint8) cv2.namedWindow('parameters') cv2.createTrackbar('value','parameters', min_range, max_range, self.update_servo_position) self.min_range = min_range self.max_range = max_range self.servos = maestro.Controller() self.current_servo = None self.current_position = min_range self.load_data() command_listener = threading.Thread(target=self.command_listener) command_listener.start() for servo in range(20): self.servos.set_range(servo, self.min_range, self.max_range) self.servos.set_speed(servo, 200) self.servos.set_acceleration(servo, 200) while self.running: try: cv2.imshow('parameters',img) cv2.waitKey(1) except KeyboardInterrupt: # Listen for control C self.exit(False)
def __init__(self): self.direction = "Current Slide" self.debugMode = True self.fingers = 0 self.frame = 0 self.camera = cv2.VideoCapture(1) self.camera.set(3,640) self.camera.set(4,480) self.posPre = 0 self.Data = {"angles less 90" : 0, "cursor" : (0, 0), "hulls" : 0, "defects" : 0, "fingers": 0, "fingers history": [0], "area": 0, } self.lastData = self.Data try: self.Vars = pickle.load(open(".config", "r")) except: print "Config file not found." exit() cv2.namedWindow("Filters") cv2.createTrackbar("erode", "Filters", self.Vars["erode"], 255, self.erode) cv2.createTrackbar("dilate", "Filters", self.Vars["dilate"], 255, self.dilate) cv2.createTrackbar("smooth", "Filters", self.Vars["smooth"], 255, self.smooth) cv2.createTrackbar("upper", "Filters", self.Vars["upper"], 255, self.onChange_upper) cv2.createTrackbar("lower", "Filters", self.Vars["lower"], 255, self.onChange_lower)
def thresholding(x): global thres, value, maxValue, img, filtro if (x == 0): thres = None filtro = img value = 127 maxValue = 255 cv2.createTrackbar('Value', windowThres, value, maxValue, fValue) cv2.createTrackbar('MaxValue', windowThres, maxValue, maxValue, fMaxValue) elif (x == 1): thres = cv2.THRESH_BINARY elif (x==2): thres = cv2.THRESH_BINARY_INV elif (x==3): thres = cv2.THRESH_TRUNC elif (x==4): thres = cv2.THRESH_TOZERO elif (x==5): thres = cv2.THRESH_TOZERO_INV if (x != 0): ret, filtro = cv2.threshold(img,value, maxValue, thres) cv2.imshow(windowTitle, filtro)
def click_radius(img_pause_rgb, img_pause_pos, rgbd_center): # Step 3: Select radius for sensor txt = "Select radius for occupancy sensor" txt2 = "Then press enter" empty_fcn = lambda _: None cv2.createTrackbar("Radius", "learn_volume", 0, 2000, empty_fcn) while 1: radius = cv2.getTrackbarPos("Radius", 'learn_volume') radius = max(1, radius)/1000. print "Radius:", radius mask = mask_radius(img_pause_pos, rgbd_center, radius) img = img_pause_rgb.copy() img = recolor_mask(img, mask) cv2.putText(img, txt, (10, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255)) cv2.putText(img, txt2, (10, 50), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255)) cv2.imshow("learn_volume", img) if cv2.waitKey(30) >= 0: break return radius
def main(): import sys try: fn = sys.argv[1] except: fn = 0 cap = video.create_capture(fn) leveln = 6 cv.namedWindow('level control') for i in xrange(leveln): cv.createTrackbar('%d'%i, 'level control', 5, 50, nothing) while True: ret, frame = cap.read() pyr = build_lappyr(frame, leveln) for i in xrange(leveln): v = int(cv.getTrackbarPos('%d'%i, 'level control') / 5) pyr[i] *= v res = merge_lappyr(pyr) cv.imshow('laplacian pyramid filter', res) if cv.waitKey(1) == 27: break print('Done')
def main(): #orig_imgs = ['photoset/cleaned/7,49/IMG_2654.JPG'] # Square, slight angle orig_imgs = glob.glob('photoset/cleaned/*/*.JPG') def img_onchange(x): filename = orig_imgs[cv2.getTrackbarPos('img', 'config')] img = cv2.imread(filename) print filename ret = get_white_rectangles(img, DEBUG=True) for r in ret: print r[1] # just the quads img_windows = ['img', 'blur', 'thresh', 'debug_display'] for i in range(len(img_windows)): w = img_windows[i] cv2.resizeWindow(w, WINDOW_WIDTH, WINDOW_HEIGHT) cv2.moveWindow(w, WINDOW_X_OFFSET + WINDOW_WIDTH * i, WINDOW_Y_OFFSET) cv2.namedWindow('config', cv2.WINDOW_AUTOSIZE) cv2.resizeWindow('config', 600, 60) cv2.createTrackbar('img', 'config', 0, len(orig_imgs), img_onchange) img_onchange(0) cv2.waitKey()
def captura(video_ruta, destino_dir): """Ciclo de captura """ assert "" != video_ruta assert "" != destino_dir assert not imagen_guardar.fich is None pausa = False cv2.namedWindow("ven1") cv2.createTrackbar("INTERVALO", "ven1", intervalo.val, 700, intervalo) cam = cv2.VideoCapture(video_ruta) _, img = cam.read() while True: tecla = 0xFF & cv2.waitKey(intervalo.val) if 97 == tecla: imagen_guardar(img, destino_dir) if 27 == tecla: break if 32 == tecla: pausa = not pausa if pausa: continue _, img = cam.read() cv2.imshow("ven1", img) cv2.destroyAllWindows()
def load_segmentation(self): ''' Load threshold values in BGR, HSV, or LAB colorspace for segmenting an image. ''' for color_space in ['hsv', 'bgr', 'lab']: self.color_space = color_space low = '/color/buoy/{}/{}_low'.format(self.color, color_space) high = '/color/buoy/{}/{}_high'.format(self.color, color_space) if not rospy.has_param(low): continue self.thresholds = [np.array(rospy.get_param(low)), np.array(rospy.get_param(high))] rospy.loginfo("BUOY - Thresholds for {} buoy loaded using {} colorspace".format( self.color, self.color_space)) if self.debug_cv: # If debug_cv is enabled, create trackbars to adjust thresholds for this buoy def change_threshold(i, i2, val): self.thresholds[i][i2] = float(val) rospy.loginfo("SETTING {} thresholds[{}][{}]={}".format(self.color, i, i2, self.thresholds[i][i2])) for i in range(len(self.thresholds[0])): cv2.createTrackbar('low {}'.format(self.color_space[i]), self.color, int(self.thresholds[0][i]), 255, lambda x, _ind=i: change_threshold(0, _ind, x)) for i in range(len(self.thresholds[1])): cv2.createTrackbar('high {}'.format(self.color_space[i]), self.color, int(self.thresholds[1][i]), 255, lambda x, _ind=i: change_threshold(1, _ind, x))
def __init__(self): # self.image_pub = rospy.Publisher("cv2_processed_image", Image,queue_size=0) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/uav_camera_down/image_raw",Image,self.callback) self.blob_detect_config = cv2.SimpleBlobDetector_Params() self.blob_detect_config.filterByArea = True self.blob_detect_config.minArea = 200 self.blob_detect_config.maxArea = 1000000 # Filter by Circularity self.blob_detect_config.filterByCircularity = True self.blob_detect_config.minCircularity = 0.3 # Filter by Convexity self.blob_detect_config.filterByConvexity = False self.blob_detect_config.minConvexity = 0.87 # Filter by Inertia self.blob_detect_config.filterByInertia = False self.blob_detect_config.minInertiaRatio = 0.01 self.blob_detect = cv2.SimpleBlobDetector(self.blob_detect_config) self.pid_controller = PID.PID() self.pid_controller.set_kp(0) self.pid_controller.set_ki(0) self.pid_controller.set_accumulated_error_max(1000) self.pid_controller.set_kd(1) cv2.namedWindow('frame') cv2.createTrackbar('Thresh_Min', 'frame', 0, 255, nothing)
def main(): try: fn = sys.argv[1] except: fn = 0 def nothing(*arg): pass cv.namedWindow('edge') cv.createTrackbar('thrs1', 'edge', 2000, 5000, nothing) cv.createTrackbar('thrs2', 'edge', 4000, 5000, nothing) cap = video.create_capture(fn) while True: flag, img = cap.read() gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) thrs1 = cv.getTrackbarPos('thrs1', 'edge') thrs2 = cv.getTrackbarPos('thrs2', 'edge') edge = cv.Canny(gray, thrs1, thrs2, apertureSize=5) vis = img.copy() vis = np.uint8(vis/2.) vis[edge != 0] = (0, 255, 0) cv.imshow('edge', vis) ch = cv.waitKey(5) if ch == 27: break print('Done')
def experiment_threshold(path): """ Launches experiment window for thresholding. :param str path: Path to the experiment image file. """ img = load_image(path) _, thresh_img = cv.threshold(img, THRESH, 255, cv.THRESH_BINARY) # Image windows for this experiment. t_window = "Threshold Experiment" o_window = "Original Image" cv.namedWindow(t_window, cv.WINDOW_AUTOSIZE) cv.namedWindow(o_window, cv.WINDOW_AUTOSIZE) # Callback for parameter slider (instantiated afterward). def thresh_callback(pos): cv.threshold(img, pos, 255, cv.THRESH_BINARY, dst=thresh_img) cv.imshow(t_window, thresh_img) return # Create the experiment and original image windows. cv.createTrackbar("Threshold", t_window, THRESH, 255, thresh_callback) cv.imshow(t_window, thresh_img) cv.imshow(o_window, img) cv.waitKey(0) return
def main(): lowThreshold = 100 higThreshold = 12 max_lowThreshold = 300 max_higThreshold = 200 mode = 1 contour_i = 10 hot_x_100 = 5000 hot_y_100 = 5000 hot_r_100 = 40 csv_filepath_large_data = 'pyNVscan_AT_CV_V3.1.csv' cv2.namedWindow('mpl_Hough',cv2.WINDOW_NORMAL) cv2.namedWindow('param',cv2.WINDOW_NORMAL) cv2.createTrackbar('Low threshold','param',100, max_lowThreshold,nothing) cv2.createTrackbar('Hig threshold','param',12, max_higThreshold,nothing) # cv2.createTrackbar('Matplotlib Mode','param',0, 2, nothing) # cv2.createTrackbar('Contour_i','param',10, 100, nothing) cv2.createTrackbar('Hot_X_100','param',5000, 10000, nothing) cv2.createTrackbar('Hot_Y_100','param',5000, 10000, nothing) cv2.createTrackbar('Hot_R_100','param',40, 10000, nothing) with open(csv_filepath_large_data,"rb") as f: my_matrix = np.loadtxt(f, delimiter=",", skiprows=0) csv_head_large = creat_CSV_Head_File(my_matrix) png_ruler_large = csv_to_PNG(my_matrix, csv_head_large, mode, contour_i, png_io) img = cv2.imdecode(np.fromstring(png_io.getvalue(), dtype=np.uint8), 1) #读内存中的二进制图像数据 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gaussian_gray = cv2.GaussianBlur(gray,(3,3),0) pzt_x, pzt_y, pzt_r = gui_CV_Number(hot_x_100, hot_y_100, hot_r_100) png_x, png_y = pztXY_to_pngXY(csv_head_large, gray, pzt_x, pzt_y) flag_hough, png_x1, png_y1, png_r1 = mpl_Hough(csv_head_large, img, gaussian_gray, png_x, png_y, pzt_r, png_ruler_large, lowThreshold, higThreshold) # initialization while(1): k=cv2.waitKey(20)&0xFF if k==27: break lowThreshold = cv2.getTrackbarPos('Low threshold','param') higThreshold = cv2.getTrackbarPos('Hig threshold','param') # mode = cv2.getTrackbarPos('Matplotlib Mode','param') # contour_i = cv2.getTrackbarPos('Contour_i','param') hot_x_100 = cv2.getTrackbarPos('Hot_X_100','param') hot_y_100 = cv2.getTrackbarPos('Hot_Y_100','param') hot_r_100 = cv2.getTrackbarPos('Hot_R_100','param') pzt_x, pzt_y, pzt_r = gui_CV_Number(hot_x_100, hot_y_100, hot_r_100) png_x, png_y = pztXY_to_pngXY(csv_head_large, gray, pzt_x, pzt_y) flag_hough, png_x1, png_y1, png_r1 = mpl_Hough(csv_head_large,img, gaussian_gray, png_x, png_y, pzt_r, png_ruler_large, lowThreshold, higThreshold) cv2.destroyAllWindows()
def SimpleTrackbar(Image, WindowName): # Generate trackbar Window Name TrackbarName = WindowName + "Trackbar" # Make Window and Trackbar cv2.namedWindow(WindowName) cv2.createTrackbar(TrackbarName, WindowName, 0, 255, nothing) # Allocate destination image Threshold = np.zeros(Image.shape, np.uint8) # Loop for get trackbar pos and process it while True: # Get position in trackbar TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName) # Apply threshold print TrackbarPos cv2.threshold(Image, TrackbarPos, 255, cv2.THRESH_BINARY, Threshold) # Show in window cv2.imshow(WindowName, Threshold) # If you press "ESC", it will return value ch = cv2.waitKey(5) if ch == 27: break cv2.destroyAllWindows() return Threshold
def __init__ (self, source = 0, training = False): self.source = 0 self.training = training self.squares = [] self.patterns = {} self.original = None self.processed = None self.last_update = clock() - 5 #self.camera = cv2.VideoCapture(self.source) for i in glob.glob('patterns/tag-[a-z]*.pgm'): print "Load", i pattern = cv2.cvtColor(cv2.imread(i), cv2.COLOR_BGR2GRAY) self.patterns[i] = pattern for transposed in range(1,4): if transposed % 2 == 0: pattern = cv2.flip(pattern, -1) pattern = cv2.transpose(pattern) #cv2.imwrite("%s-t%d.pgm" % (i, transposed), pattern) self.patterns["%s-t%d" % (i, transposed)] = pattern if self.training: cv2.namedWindow('processed') cv2.createTrackbar('erosion', 'processed', CONFIG_DEFAULT_ERODE, 8, self._update) cv2.createTrackbar('minarea', 'processed', CONFIG_DEFAULT_MINAREA, 10000, self._update) cv2.createTrackbar('level1', 'processed', CONFIG_DEFAULT_LEVEL1, 1000, self._update) cv2.createTrackbar('level2', 'processed', CONFIG_DEFAULT_LEVEL2, 500, self._update) cv2.createTrackbar('threshold', 'processed', CONFIG_DEFAULT_THRESHOLD, 1000, self._update)
def thresholdTrackBar(Image, WindowName): # Generate trackbar Window Name TrackbarName = WindowName + "Trackbar" # Make Window and Trackbar cv2.namedWindow(WindowName,cv2.CV_WINDOW_AUTOSIZE) cv2.createTrackbar(TrackbarName, WindowName, 182, 255, nothing) #Reduce para visualizarlo mejor Imageres = cv2.resize(Image,(Image.shape[1]/4,Image.shape[0]/4)) # Allocate destination image Threshold2 = np.zeros(Imageres.shape, np.uint8) while True: # Get position in trackbar TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName) # Apply threshold cv2.threshold(Imageres, TrackbarPos, 255, cv2.THRESH_BINARY_INV, Threshold2) # Show in window cv2.imshow(WindowName, Threshold2) # If you press "ESC", it will return value ch = cv2.waitKey(5) if ch == 27 or ch == ord(' '): break cv2.destroyAllWindows() #Como se ha hecho con la imagen reducida, se coge el umbral y se pasa por la imagen real a devolver ret,Threshold = cv2.threshold(Image,TrackbarPos,255,cv2.THRESH_BINARY_INV) return Threshold
def createTestFrame(window_name, parameters): cv2.namedWindow(window_name) for k, v in parameters.iteritems(): if len(v) > 2: cv2.createTrackbar(k+v[2].func_name,window_name,v[0],v[1],dummy) else: cv2.createTrackbar(k, window_name,v[0],v[1],dummy)
def __init__(self, init_param = False): if init_param: #init_param allows us to instantiate the HR object in different contexts, i.e in WritingDemo.py pass else: rospy.init_node('handwriting_recognition', anonymous=True) rospy.Subscriber('usb_cam/image_raw', Image, self.img_callback) self.bridge = CvBridge() rospack = rospkg.RosPack() self.PARAMS_PATH = rospack.get_path('edwin') self.img = cv2.imread(self.PARAMS_PATH + '/params/test_imgs/digits.png') self.pub = rospy.Publisher('word_publish',String,queue_size=10) self.detect = True cv2.namedWindow('image') cv2.createTrackbar('X','image',0,255,self.nothing) cv2.setTrackbarPos('X','image',255) cv2.createTrackbar('Y','image',0,255,self.nothing) cv2.setTrackbarPos('Y','image',7) self.test_data = np.zeros((200,200),np.uint8) self.test_filled = 0 # print os.getcwd() # Defines vars for keeping track of new words self.last_word = '' self.last_time = time.time() self.curr_data = '' self.found_word = False
import cv2 import numpy as np from matplotlib import pyplot as plt def nop(x): pass cv2.namedWindow('Blending') cv2.createTrackbar("Alpha", "Blending" , 0,10, nop) cv2.createTrackbar("Beta" , "Blending", 0,10, nop) cv2.createTrackbar("Gamma", "Blending", 0,10, nop) img1 = cv2.imread('C:\\Users\\student\\Desktop\\33.jpg') img2 = cv2.imread('C:\\Users\\student\\Desktop\\44.jpg') new_w, new_h = 640, 640 img1 = cv2.resize(img1, (new_w, new_h), interpolation = cv2.INTER_AREA) img2 = cv2.resize(img2, (new_w, new_h), interpolation = cv2.INTER_AREA) while (1): a = cv2.getTrackbarPos("Alpha", "Blending") b = cv2.getTrackbarPos("Beta", "Blending") c = cv2.getTrackbarPos("Gamma", "Blending") dst = cv2.addWeighted(img1,a/10,img2,b/10, c/10) cv2.imshow('dst',dst) k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows()
class Controller(object): capture = cv2.VideoCapture("output.mkv") drone = libardrone.ARDrone() time1 = 0 time1Set = False QRFoundThisIteration = False ''' classdocs ''' state = DroneState.State() LR = 0 BF = 0 UD = 0 ROT = 0 time1 = 0 trackbarName = "Move" trackbarLRName = "LR" trackbarBFName = "BF" trackbarUDName = "UD" trackbarROTName = "ROT" trackbartime1Name = "time1" def nothing(self): pass cv2.namedWindow(trackbarName) cv2.resizeWindow(trackbarName, 780, 780) cv2.createTrackbar(trackbarLRName, trackbarName, 0, 1000, nothing) cv2.createTrackbar(trackbarBFName, trackbarName, 0, 1000, nothing) cv2.createTrackbar(trackbarUDName, trackbarName, 0, 1000, nothing) cv2.createTrackbar(trackbarROTName, trackbarName, 0, 1000, nothing) cv2.setTrackbarPos(trackbarLRName, trackbarName, 0) cv2.setTrackbarPos(trackbarBFName, trackbarName, 0) cv2.setTrackbarPos(trackbarUDName, trackbarName, 0) cv2.setTrackbarPos(trackbarROTName, trackbarName, 0) def updateTrackbarValues(self): self.LR = cv2.getTrackbarPos(self.trackbarLRName, self.trackbarName) / float(1000) self.BF = cv2.getTrackbarPos(self.trackbarBFName, self.trackbarName) / float(1000) self.UD = cv2.getTrackbarPos(self.trackbarUDName, self.trackbarName) / float(1000) self.ROT = cv2.getTrackbarPos(self.trackbarROTName, self.trackbarName) / float(1000) def __init__(self): ''' Constructor ''' def main(self): self.initializeCamera() analyzer = oa.ObjectAnalyzer() #imageCreaterObj = IC.ImageCreater() while (True): if cv2.waitKey(1) & 0xFF == ord('w'): print "Take off" break self.drone.takeoff() time.sleep(5) continueGrabbing = True #while (self.capture.isOpened()): while (True): #imageCreaterObj.updateTrackbarValues() #imageCreaterObj.drawEllipse() #frame = imageCreaterObj.getImage() #grabbed, readFrame = self.capture.read() #if grabbed: # imshow("Webcam", readFrame) if cv2.waitKey(1) & 0xFF == ord('1'): self.state.circleReached = 1 print "1" elif cv2.waitKey(1) & 0xFF == ord('2'): self.state.circleReached = 2 print "2" elif cv2.waitKey(1) & 0xFF == ord('3'): self.state.circleReached = 3 print "3" elif cv2.waitKey(1) & 0xFF == ord('4'): self.state.circleReached = 4 print "4" elif cv2.waitKey(1) & 0xFF == ord('5'): self.state.circleReached = 5 print "5" elif cv2.waitKey(1) & 0xFF == ord('6'): self.state.circleReached = 6 print "6" if cv2.waitKey(1) & 0xFF == ord('w'): if continueGrabbing: continueGrabbing = False print "Pause" else: continueGrabbing = True print "Continue" grabbed, frame = self.drone.readVideo() #if continueGrabbing: # grabbed, frame = self.capture.read() # if not grabbed: print("Frame not grabbed") continue #imshow("Frame",frame) self.getQRResult(frame) if self.QRFoundThisIteration: analyzer.advancedCircleScanning(frame, self.state) self.QRFoundThisIteration = False #Reset for next loop else: analyzer.normalCircleScanning(frame, self.state) #print "CircleSeen: ", self.state.circleSeen self.updateTrackbarValues() self.navigate() self.state.updateCounters() if self.state.QRCodeSeen: print "QRAboveCenter", self.state.QRAboveCenter() print "QRUnderCenter", self.state.QRUnderCenter() print "QRLeftOfCenter", self.state.QRLeftOfCenter() print "QRRightOfCenter", self.state.QRRightOfCenter() print "Distance", self.state.QRdistance print "\n" if cv2.waitKey(1) & 0xFF == ord('q'): self.drone.land() break # When everything done, release the capture #self.capture.release() cv2.destroyAllWindows() #self.drone.land() def initializeCamera(self): #self.capture.open("tcp://192.168.1.1:5555") self.capture.open("output.mkv") def getQRResult(self, frame): result = findAndReadQR(frame) if result is not None: self.state.QRCodeSeen = True self.state.QRdistance = result.distance self.state.mostRecentQR = result self.state.QRxCoor = result.x self.state.QRyCoor = result.y self.state.QRdata = result.data self.state.resetQRCounter() self.state.QRRotatedRight = result.QRRotatedRight self.state.QRRotatedLeft = result.QRRotatedLeft self.state.QRRightside = result.rightSide self.state.QRLeftside = result.leftSide self.state.QRLowerside = result.lowerSide self.state.QRUpperside = result.upperSide def navigate(self): if not self.state.flownOnce: print "FLY " self.state.flownOnce = True self.drone.asyncCommand(0, -0.15, 0.35, 0, 0.75, 0) time.sleep(1.2) self.drone.asyncCommand(0, 0.1, 0, 0, 0.3, 0) time.sleep(1.8) print "afterFly" #Hover in air to find circle. if not self.time1Set: self.time1 = time.time() self.time1Set = True if time.time() - self.time1 < 0.15: #print "LR: ", self.LR, " BF: ", self.BF, " UD: ", self.UD, " ROT: ", self.ROT self.drone.asyncCommand(self.LR, self.BF, self.UD, self.ROT, 0.05, 0.05) return self.time1Set = False #print "Ellipse seen" #Are the ellipse in the center of the screen? if self.state.QRCodeSeen: #We don't give a shit if the drone is centered at the ellipse center print "QR" if self.state.QRCentered(): if self.state.QRminDist(): print "Go through the ring" self.drone.asyncCommand(0, 0, 0.7, 0, 1, 0) time.sleep(1.1) self.drone.asyncCommand(0, -0.5, 0, 0, 1, 0) self.state.QRCodeSeen = False else: print "Go closer to the ring" self.drone.asyncCommand(0, -0.1, 0, 0, 0.5, 0) else: lf = 0 bf = 0 ud = 0 rot = 0 timer1 = 0.1 if self.state.QRAboveCenter(): print "Fly up" ud = 0.7 if self.state.QRUnderCenter(): print "Fly down" ud = -0.4 if self.state.QRRightOfCenter(): lf = 0.15 print "Fly right" if self.state.QRLeftOfCenter(): print "Fly left" lf = -0.15 #print "lf: ", lf, " bf: ", bf, " rot: ",rot,#\n" self.drone.asyncCommand(lf, bf, ud, rot, timer1, 0.5) if self.state.circleSeen and self.state.QRCodeSeen: lf = 0 bf = 0 ud = 0 rot = 0 timer1 = 0.1 if self.state.droneRightOfCenter(): lf = -0.15 rot = -0.05 print "Fly Left" if self.state.droneLeftOfCenter(): print "Fly Right" lf = 0.15 rot = 0.05 #print "lf: ", lf, " bf: ", bf, " rot: ",rot,#\n" self.drone.asyncCommand(lf, bf, ud, rot, timer1, 0.5) if self.state.circleSeen and not self.state.QRCodeSeen: #We are able to detect a circle #print "Circle seen" #Check if circle is in the center of the image if not self.state.droneRightOfCenter( ) and not self.state.droneLeftOfCenter(): if self.state.droneCentered(): if self.state.circleDiameterEqualToHeight(): self.drone.asyncCommand(0, -0.3, 0, 0, 1, 0.75) print "RightInCenter" self.state.circleSeen = False #self.drone.asyncCommand(0, 0, -0.4, 0, 0.5, 0) else: self.drone.asyncCommand(0, -0.5, 0.05, 0, 0.2, 0.75) print "DroneCentered" else: lf = 0 bf = 0 ud = 0 rot = 0 timer1 = 0.1 if self.state.droneAboveCenter(): print "Fly down" ud = -0.4 if self.state.droneUnderCenter(): print "Fly up" ud = 0.7 if self.state.droneRightOfCenter(): lf = -0.15 print "Fly Left" if self.state.droneLeftOfCenter(): print "Fly Right" lf = 0.15 #print "lf: ", lf, " bf: ", bf, " rot: ",rot,#\n" self.drone.asyncCommand(lf, bf, ud, rot, timer1, 0.5) else: #self.drone.asyncCommand(0, 0, 0, -0.1, 0.05, 0.05) print "Nothing found"
if not pista: pts = np.array(pxpista, dtype="float32") imagen = four_point_transform(imagen, pts) height, width, _ = imagen.shape #Se le aplican diferentes filtros imagen = cv2.bilateralFilter(imagen, 5, 75, 75) #5 o 9, mas grande mas lento imagen = noise(imagen) hsv = cv2.cvtColor(imagen, cv2.COLOR_BGR2HSV) if (HSV): if (not ON): #Creamos una ventana llamada 'HSV' en la que habra todos los sliders cv2.namedWindow('HSV') cv2.createTrackbar('H min', 'HSV', 0, 180, nothing) cv2.createTrackbar('H max', 'HSV', 0, 180, nothing) cv2.createTrackbar('S min', 'HSV', 0, 255, nothing) cv2.setTrackbarPos('S min', 'HSV', 2) cv2.createTrackbar('S max', 'HSV', 0, 255, nothing) cv2.setTrackbarPos('S max', 'HSV', 255) cv2.createTrackbar('V min', 'HSV', 0, 255, nothing) cv2.createTrackbar('V max', 'HSV', 0, 255, nothing) cv2.setTrackbarPos('V max', 'HSV', 255) ON = True #Los valores maximo y minimo de H,S y V se guardan en funcion de la posicion de los sliders hMin = cv2.getTrackbarPos('H min', 'HSV') hMax = cv2.getTrackbarPos('H max', 'HSV') sMin = cv2.getTrackbarPos('S min', 'HSV') sMax = cv2.getTrackbarPos('S max', 'HSV')
from __future__ import print_function import cv2 as cv import argparse max_lowThreshold = 100 window_name = 'Edge Map' title_trackbar = 'Min Threshold:' ratio = 3 kernel_size = 3 def CannyThreshold(val): low_threshold = val img_blur = cv.blur(src_gray, (3,3)) detected_edges = cv.Canny(img_blur, low_threshold, low_threshold*ratio, kernel_size) mask = detected_edges != 0 dst = src * (mask[:,:,None].astype(src.dtype)) cv.imshow(window_name, dst) parser = argparse.ArgumentParser(description='Code for Canny Edge Detector tutorial.') parser.add_argument('--input', help='Path to input image.', default='../data/fruits.jpg') args = parser.parse_args() src = cv.imread(args.input) if src is None: print('Could not open or find the image: ', args.input) exit(0) src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) cv.namedWindow(window_name) cv.createTrackbar(title_trackbar, window_name , 0, max_lowThreshold, CannyThreshold) CannyThreshold(0) cv.waitKey()
import cv2 import numpy as np def nothing(x): pass # capture from webcam vid = cv2.VideoCapture(0) cv2.namedWindow('trackbarsL') cv2.namedWindow('trackbarsU') # create lower trackbars for color change cv2.createTrackbar('LH', 'trackbarsL', 0, 179, nothing) cv2.createTrackbar('LS', 'trackbarsL', 0, 255, nothing) cv2.createTrackbar('LV', 'trackbarsL', 0, 255, nothing) # create upper trackbars for color change cv2.createTrackbar('UH', 'trackbarsU', 0, 179, nothing) cv2.createTrackbar('US', 'trackbarsU', 0, 255, nothing) cv2.createTrackbar('UV', 'trackbarsU', 0, 255, nothing) while vid.isOpened(): ret, frame = vid.read() # resize frame frame = cv2.resize(frame, (800, 450)) # flip frames frame = cv2.flip(frame, 1)
def adjust_settings(cap, image_settings): cv2.namedWindow("Ventana") cv2.resizeWindow("Ventana", 500, 200) #Sliders para ajuste del tamanio del area de trabajo para recortar cosas #por fuera del plato. Estos objetos meten ruido en la deteccion cv2.createTrackbar("Xmax", "Ventana", 519, 640, empty) cv2.createTrackbar("Xmin", "Ventana", 112, 640, empty) cv2.createTrackbar("Ymax", "Ventana", 420, 480, empty) cv2.createTrackbar("Ymin", "Ventana", 87, 480, empty) #Umbrales de deteccion de contorno utilizados en Canny cv2.namedWindow("Umbrales") cv2.resizeWindow("Umbrales", 500, 150) cv2.createTrackbar("Umbral1", "Umbrales", 120, 500, empty) cv2.createTrackbar("Umbral2", "Umbrales", 315, 500, empty) #Umbral para comparacion de escala de grises #la idea es poner en negro todos los pixeles con luminocidad menor #a este umbral cv2.createTrackbar("Ugr", "Umbrales", 245, 255, empty) #Umbral de area (no esta en uso) buscaba un umbral minimo en un contorno para decir que es la pelota cv2.createTrackbar("Area", "Umbrales", 3000, 10000, empty) while (True): #obtencion de los valores de los sliders x_min = cv2.getTrackbarPos("Xmin", "Ventana") x_max = cv2.getTrackbarPos("Xmax", "Ventana") y_min = cv2.getTrackbarPos("Ymin", "Ventana") y_max = cv2.getTrackbarPos("Ymax", "Ventana") u_1 = cv2.getTrackbarPos("Umbral1", "Umbrales") u_2 = cv2.getTrackbarPos("Umbral2", "Umbrales") u_gris = cv2.getTrackbarPos("Ugr", "Umbrales") u_area = cv2.getTrackbarPos("Area", "Umbrales") u_area = 2000 success, img = cap.read() #creo mascara llena de 0 para recortar imagen mask = np.zeros(img.shape[:2], dtype="uint8") #creo rectangulo para utilizar como mascara #esta mascara esta parametrizada con los slider para poder dejar afuera obstalucos cv2.rectangle(mask, (x_min, y_min), (x_max, y_max), 255, -1) #enmascaramos la imagen de video masked = cv2.bitwise_and(img, img, mask=mask) imagen_recortada = masked #invierto color a escala de grises invert = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY) # Lo que hace es normalizar la imagen en brillo para aprovechar todo el rango dinamico #no esta en uso, no aportaba mejoras significativas #aplico histograma #equ = cv2.equalizeHist(invert) #cv2.imshow('Ecualizadas', equ) #invert=equ #agrego mascara para detectar los blancos _, binarizada = cv2.threshold(invert, u_gris, 255, cv2.THRESH_BINARY) #detecto contornos canny = cv2.Canny(binarizada, u_1, u_2) #dilato los contornos canny = cv2.dilate(canny, None, iterations=1) #supresion de sombras #_,sombra=cv2.threshold(canny,254,255,cv2.THRESH_BINARY) #obtengo los contornos #podemos probar otros algoritmos de deteccion de contornos contornos, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cv2.imshow("Camara", img) cv2.imshow("Canny", canny) cv2.imshow("Imagen Recortada", imagen_recortada) if cv2.waitKey(1) & 0xFF == ord('q'): cv2.destroyAllWindows() break return x_min, x_max, y_min, y_max, u_1, u_2, u_gris, u_area
import sys import cv2 DEFAULT_QUALITY = 95 WINDOW_FLAGS = cv2.WINDOW_AUTOSIZE # (too) large window for large image WINDOW_FLAGS = cv2.WINDOW_GUI_NORMAL # nice, auto scales... same as WINDOW_NORMAL? WINDOW_FLAGS = cv2.WINDOW_KEEPRATIO # looks like other flags also keep the ratio... WINDOW_FLAGS = cv2.WINDOW_NORMAL def update_quality(value): global orig_image data = cv2.imencode('.jpg', orig_image, [cv2.IMWRITE_JPEG_QUALITY, value])[1] print('Quality: {}, data size: {:,}'.format(value, len(data))) image = cv2.imdecode(data, cv2.IMREAD_COLOR) cv2.imshow('jpeg_preview', image) orig_image = cv2.imread(sys.argv[1]) cv2.namedWindow('jpeg_preview', WINDOW_FLAGS) cv2.createTrackbar('Q', 'jpeg_preview', DEFAULT_QUALITY, 100, update_quality) update_quality(DEFAULT_QUALITY) while True: key = cv2.waitKey(10) & 0xff # print(key) if key in (27, ord('q')): break
import cv2 import numpy as np cap = cv2.VideoCapture(2) def nothing(x): pass # Creating a window for later use cv2.namedWindow('result') # Starting with 100's to prevent error while masking h,s,v = 100,100,100 # Creating track bar cv2.createTrackbar('h', 'result',0,179,nothing) cv2.createTrackbar('s', 'result',0,255,nothing) cv2.createTrackbar('v', 'result',0,255,nothing) while(1): _, frame = cap.read() #converting to HSV hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) # get info from track bar and appy to result h = cv2.getTrackbarPos('h','result') s = cv2.getTrackbarPos('s','result') v = cv2.getTrackbarPos('v','result')
if __name__ == '__main__': hsv_map = np.zeros((180, 256, 3), np.uint8) h, s = np.indices(hsv_map.shape[:2]) hsv_map[:,:,0] = h hsv_map[:,:,1] = s hsv_map[:,:,2] = 255 hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2BGR) cv2.imshow('hsv_map', hsv_map) cv2.namedWindow('hist', 0) hist_scale = 10 def set_scale(val): global hist_scale hist_scale = val cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale) try: fn = sys.argv[1] except: fn = 0 cam = video.create_capture(fn, fallback='synth:bg=../cpp/baboon.jpg:class=chess:noise=0.05') while True: flag, frame = cam.read() cv2.imshow('camera', frame) small = cv2.pyrDown(frame) hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV) dark = hsv[...,2] < 32
d0 = dv / 10.0 aplicaFiltro() image = cv2.imread("lenna.png", 0) cv2.imshow("original", image) image = np.float32(image) height, width = image.shape dft_M = cv2.getOptimalDFTSize(height) dft_N = cv2.getOptimalDFTSize(width) padded = cv2.copyMakeBorder(image, 0, dft_M-height,0,dft_N-width, cv2.BORDER_CONSTANT, 0) + 1 padded = np.log(padded) complex = cv2.dft(padded,flags=cv2.DFT_COMPLEX_OUTPUT) complex = np.fft.fftshift(complex) img_back = 20*np.log(cv2.magnitude(complex[:,:,0],complex[:,:,1])) cv2.imshow("fft", np.uint8(img_back)) cv2.imshow("homomorfico", image) trackbarName = "GL " cv2.createTrackbar(trackbarName,"homomorfico",g,100,setgl) trackbarName = "GH " cv2.createTrackbar(trackbarName,"homomorfico",g,100,setgh) trackbarName = "C " cv2.createTrackbar(trackbarName,"homomorfico",cv,100,setc) trackbarName = "D0 " cv2.createTrackbar(trackbarName,"homomorfico",dv,dft_M,setd0) cv2.waitKey(0) cv2.destroyAllWindows()
(128, 0, 0), (128, 128, 0), (0, 128, 0), (128, 0, 128), (0, 128, 128), (0, 0, 128)] class_rgb = np.array(class_rgb) # If there are still more classes, add new colors randomly num_colors_missing = len(CLASS_LIST) - len(class_rgb) if num_colors_missing > 0: more_colors = np.random.randint(0, 255 + 1, size=(num_colors_missing, 3)) class_rgb = np.vstack([class_rgb, more_colors]) # create window cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_KEEPRATIO) cv2.resizeWindow(WINDOW_NAME, 1000, 700) cv2.setMouseCallback(WINDOW_NAME, mouse_listener) # selected image cv2.createTrackbar(TRACKBAR_IMG, WINDOW_NAME, 0, last_img_index, set_img_index) # selected class if last_class_index != 0: cv2.createTrackbar(TRACKBAR_CLASS, WINDOW_NAME, 0, last_class_index, set_class_index) # initialize set_img_index(0) edges_on = False display_text('Welcome!\n Press [h] for help.', 4000) # loop while True: color = class_rgb[class_index].tolist()
def initializeTrackbars_side_r(intialTracbarVals): cv2.namedWindow("Trackbars_side_r") cv2.resizeWindow("Trackbars_side_r", 360, 360) cv2.createTrackbar("a", "Trackbars_side_r", intialTracbarVals[0], 100, nothing) cv2.createTrackbar("b", "Trackbars_side_r", intialTracbarVals[1], 100, nothing) cv2.createTrackbar("c", "Trackbars_side_r", intialTracbarVals[2], 100, nothing) cv2.createTrackbar("d", "Trackbars_side_r", intialTracbarVals[3], 100, nothing) cv2.createTrackbar("e", "Trackbars_side_r", intialTracbarVals[4], 100, nothing) cv2.createTrackbar("f", "Trackbars_side_r", intialTracbarVals[5], 100, nothing) cv2.createTrackbar("g", "Trackbars_side_r", intialTracbarVals[6], 100, nothing) cv2.createTrackbar("h", "Trackbars_side_r", intialTracbarVals[7], 100, nothing)
#!/usr/bin/env python import cv2 import numpy as np import rospy from std_msgs.msg import String def nothing(x): pass cv2.namedWindow("Trackbars") cv2.createTrackbar("L-H", "Trackbars", 0, 255, nothing) cv2.createTrackbar("L-S", "Trackbars", 0, 255, nothing) cv2.createTrackbar("L-V", "Trackbars", 0, 255, nothing) cv2.createTrackbar("U-H", "Trackbars", 255, 255, nothing) cv2.createTrackbar("U-S", "Trackbars", 255, 255, nothing) cv2.createTrackbar("U-V", "Trackbars", 255, 255, nothing) pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): img = cv2.imread('objek-1.png') data = img.shape width = data[1] height = data[0] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh1 = cv2.threshold(gray, 127, 255, 0)
def on_high_V_thresh_trackbar(val): global low_V global high_V high_V = val high_V = max(high_V, low_V + 1) cv.setTrackbarPos(high_V_name, window_detection_name, high_V) parser = argparse.ArgumentParser(description='Code for Thresholding Operations using inRange tutorial.') parser.add_argument('--camera', help='Camera divide number.', default=0, type=int) args = parser.parse_args() cap = cv.VideoCapture(args.camera) cv.namedWindow(window_capture_name) cv.namedWindow(window_detection_name) cv.createTrackbar(low_H_name, window_detection_name, low_H, max_value_H, on_low_H_thresh_trackbar) cv.createTrackbar(high_H_name, window_detection_name, high_H, max_value_H, on_high_H_thresh_trackbar) cv.createTrackbar(low_S_name, window_detection_name, low_S, max_value, on_low_S_thresh_trackbar) cv.createTrackbar(high_S_name, window_detection_name, high_S, max_value, on_high_S_thresh_trackbar) cv.createTrackbar(low_V_name, window_detection_name, low_V, max_value, on_low_V_thresh_trackbar) cv.createTrackbar(high_V_name, window_detection_name, high_V, max_value, on_high_V_thresh_trackbar) while True: ret, frame = cap.read() if frame is None: break #frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV) #frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V)) frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV) h, s, v = cv.split(frame_HSV)
# Define 'nothing' function def nothing(x): pass camSet = 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method=' + str( flip) + ' ! video/x-raw, width=' + str(dispW) + ', height=' + str( dispH ) + ', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink' cam = cv2.VideoCapture(camSet) # Introduce Window and Trackbar-(0, not start value its the initial setting on trackbar) cv2.namedWindow('piCam') cv2.createTrackbar('xVal', 'piCam', 25, dispW, nothing) cv2.createTrackbar('yVal', 'piCam', 25, dispH, nothing) cv2.createTrackbar('Width', 'piCam', 25, dispW, nothing) cv2.createTrackbar('Height', 'piCam', 25, dispH, nothing) cv2.FOn while True: ret, frame = cam.read() # Reading Trackbar (x value and y value) xVal = cv2.getTrackbarPos('xVal', 'piCam') yVal = cv2.getTrackbarPos('yVal', 'piCam') Width = cv2.getTrackbarPos('Width', 'piCam') Height = cv2.getTrackbarPos('Height', 'piCam') # Use trackbar to place circle cv2.circle(frame, (xVal, yVal), 5, (255, 0, 0), -1)
import numpy as np import cv2 as cv def saturated(value): if value > 255: value = 255 elif value < 0: value = 0 return value def on_level_change(pos): img[:] = saturated(pos * 16) cv.imshow('image', img) img = np.zeros((400, 400), np.uint8) cv.namedWindow('image') cv.createTrackbar('level', 'image', 0, 16, on_level_change) cv.imshow('image', img) cv.waitKey() cv.destroyAllWindows()
import numpy as np import cv2 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) switch = '0 : OFF\n 1 : ON' cv2.createTrackbar(switch, 'image', 0, 1, nothing) while True: cv2.imshow('image', img) k = cv2.waitKey(1) if k == 27: break b = cv2.getTrackbarPos('B', 'image') g = cv2.getTrackbarPos('G', 'image') r = cv2.getTrackbarPos('R', 'image') s = cv2.getTrackbarPos(switch, 'image') if s == 0: img[:] = 0 else: img[:] = [b, g, r] cv2.destroyAllWindows()
import cv2 import numpy as np def change_color(x): print(x) img = np.zeros((300, 512, 3), np.uint8) cv2.namedWindow('image') cv2.createTrackbar('B', 'image', 0, 255, change_color) cv2.createTrackbar('G', 'image', 0, 255, change_color) cv2.createTrackbar('R', 'image', 0, 255, change_color) cv2.createTrackbar('O:OFF, 1:ON', 'image', 0, 1, change_color) while True: cv2.imshow('image', img) key = cv2.waitKey(1) & 0xFF b = cv2.getTrackbarPos('B', 'image') g = cv2.getTrackbarPos('G', 'image') r = cv2.getTrackbarPos('R', 'image') s = cv2.getTrackbarPos('O:OFF, 1:ON', 'image') if s == 0: img[:] = 0 else: img[:] = [b, g, r] if key == 27: break
vl = v path = str(sys.argv[1]) if str(sys.argv[2]) == "img": img = cv2.imread(path) else: vid = cv2.VideoCapture(path) vid.set(cv2.CAP_PROP_POS_FRAMES, int(str(sys.argv[2]))) s, img = vid.read() hl, sl, vl = 0, 0, 0 hu, su, vu = 255, 255, 255 cv2.imshow("mask", img) cv2.imshow("img", img) cv2.createTrackbar("HL", "mask", hl, 180, val2) cv2.createTrackbar("HH", "mask", hu, 180, val1) cv2.createTrackbar("SL", "mask", sl, 255, val4) cv2.createTrackbar("SH", "mask", su, 255, val3) cv2.createTrackbar("VL", "mask", vl, 255, val6) cv2.createTrackbar("VH", "mask", vu, 255, val5) while(1): low = np.array([hl, sl, vl]) high = np.array([hu, su, vu]) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, low, high) cv2.imshow("mask", mask) resulth = np.zeros(img.shape, dtype=np.uint8) resulth = cv2.bitwise_and(img, img, mask=mask) cv2.imshow("kleur", resulth) if cv2.waitKey(1) & 0xFF == ord('q'):
def createTrackbars(): # create tracker window cv2.namedWindow(trackbarWindowName,0) TrackbarName = '' print(TrackbarName, 'H_MIN', H_MIN) print(TrackbarName, 'H_MAX', H_MAX) print(TrackbarName, 'S_MIN', S_MIN) print(TrackbarName, 'S_MAX', S_MAX) print(TrackbarName, 'V_MIN', V_MIN) print(TrackbarName, 'V_MAX', V_MAX) cv2.createTrackbar("H_MIN", trackbarWindowName, H_MIN, H_MAX, on_trackbar ) cv2.createTrackbar("H_MAX", trackbarWindowName, H_MAX, H_MAX, on_trackbar ) cv2.createTrackbar("S_MIN", trackbarWindowName, S_MIN, S_MAX, on_trackbar ) cv2.createTrackbar("S_MAX", trackbarWindowName, S_MAX, S_MAX, on_trackbar ) cv2.createTrackbar("V_MIN", trackbarWindowName, V_MIN, V_MAX, on_trackbar ) cv2.createTrackbar("V_MAX", trackbarWindowName, V_MAX, V_MAX, on_trackbar )
I = cv2.imread(sys.argv[1], cv2.CV_LOAD_IMAGE_GRAYSCALE) else: print "Usge:python morphologyEx.py imageFile" #显示原图 cv2.imshow("I", I) #结构元半径,迭代次数 r, i = 1, 1 MAX_R, MAX_I = 20, 20 #显示形态学处理的效果的窗口 cv2.namedWindow("morphology", 1) def nothing(*arg): pass #调节结构元半径 cv2.createTrackbar("r", "morphology", r, MAX_R, nothing) #调节迭代次数 cv2.createTrackbar("i", "morphology", i, MAX_I, nothing) while True: #得到当前的r值 r = cv2.getTrackbarPos('r', 'morphology') #得到当前的i值 i = cv2.getTrackbarPos('i', 'morphology') #创建结构元 s = cv2.getStructuringElement(cv2.MORPH_RECT, (2 * r + 1, 2 * r + 1)) #形态学处理 d = cv2.morphologyEx(I, cv2.MORPH_GRADIENT, s, iterations=i) #显示效果 cv2.imshow("morphology", d) cv2.imwrite("open.jpg", d) ch = cv2.waitKey(5)
def dictLines(lines): lines_dict = defaultdict(lambda: 0, ) for line in lines: rho = line[0][0] theta = line[0][1] theta_d = int(theta * 180 / np.pi) lines_dict[theta_d] += 1 return lines_dict # Creating a window for HSV track bars cv2.namedWindow('HSV_TrackBar') # Creating track bar cv2.createTrackbar('thresh', 'HSV_TrackBar', 80, 255, nothing) cv2.createTrackbar('min', 'HSV_TrackBar', 110, 255, nothing) kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) while (1): thresh = cv2.getTrackbarPos('thresh', 'HSV_TrackBar') min = cv2.getTrackbarPos('min', 'HSV_TrackBar') # Capture frames from the camera ret, originalFrame = cap.read() frame = originalFrame[:, 0:300] ########################################## originalGray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
#image = cv.CreateImageHeader((depth.shape[1], depth.shape[0]),cv.IPL_DEPTH_8U,1) #cv.SetData(image, depth.tostring(),depth.dtype.itemsize * depth.shape[1]) cv.imshow('Depth', depth) cv.setMouseCallback("Depth", coords_mouse_disp, depth) #cv.imshow("perwitt",prewitt) #cv.setMouseCallback("Depth image",coords_mouse_disp,depth) def show_video(): array, _ = freenect.sync_get_video() array = cv.cvtColor(array, cv.COLOR_RGB2BGR) cv.imshow('Video', array) cv.namedWindow('Depth') cv.namedWindow('Video') cv.createTrackbar('threshold', 'Depth', threshold, 500, change_threshold) cv.createTrackbar('depth', 'Depth', current_depth, 2048, change_depth) #print('Press ESC in window to stop') while 1: show_depth() show_video() k = cv.waitKey(5) & 0xFF if k == 27: break cv.destroyAllWindows()
def run(): cv2.namedWindow('frame', cv2.WINDOW_NORMAL) cv2.resizeWindow('frame', 640, 480) cv2.createTrackbar('X', 'frame', OFFSET_ALONG, 1000, update_ALONG) cv2.createTrackbar('Y', 'frame', OFFSET_ACROSS, 1000, update_ACROSS) while (True): # Capture frame-by-frame ret, frame = cap.read() # print (frame.shape) h, w, _ = frame.shape # Our operations on the frame come here gray_d = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.undistort(gray_d, camera_matrix, dist_coeffs) if USE_UNDISTORT else gray_d res = cv2.aruco.detectMarkers(gray, dictionary) # print(res[0],res[1],len(res[2])) if len(res[0]) > 0: cv2.aruco.drawDetectedMarkers(gray, res[0], res[1]) data = { 'updates': [], 'size': { 'width': w, 'height': h } # for aspect ratio calculation } # print(res[0], res[1]) for (fids, index) in zip(res[0], res[1]): fid = fids[0] if int(index[0]) == 0: # floor fiducial! global ever_seen_floor if not ever_seen_floor: print("found floor!") ever_seen_floor = True d = sum([ dist(fid[a], fid[b]) for (a, b) in zip((0, 1, 2, 3), (1, 2, 3, 0)) ]) / 4 # average of all four edge lengths global floor_scale floor_scale = d / FLOOR_FIDUCIAL_EDGE_SIZE data['floorFiducial'] = [[int(pt[0]), int(pt[1])] for pt in fid] elif int(index[0]) <= MAX_BOTS: # print("found non-floor!") center = sum(fid) / 4.0 front = (fid[0] + fid[1]) / 2.0 d = sum([ dist(fid[a], fid[b]) for (a, b) in zip((0, 1, 2, 3), (1, 2, 3, 0)) ]) / 4 data['updates'].append({ 'id': int(index[0]), 'fiducialLocation': [[int(pt[0]), int(pt[1])] for pt in fid], 'fiducialScale': d / TRACK_FIDUCIAL_EDGE_SIZE, 'angle': math.atan2(front[1] - center[1], front[0] - center[0]) }) data['floorScale'] = floor_scale for update in data['updates']: Sf = update['fiducialScale'] Sr = floor_scale angle = update['angle'] x_factor = OFFSET_ALONG * math.cos( angle) - OFFSET_ACROSS * math.sin(angle) y_factor = OFFSET_ALONG * math.sin( angle) + OFFSET_ACROSS * math.cos(angle) robotLocation = [ (pt[0], pt[1]) for pt in update['fiducialLocation'] ] if not USE_UNDISTORT else [ (int((float(pt[0] - w / 2) / Sf + x_factor) * Sr + w / 2), int((float(pt[1] - h / 2) / Sf + y_factor) * Sr + h / 2)) for pt in update['fiducialLocation'] ] update['robotLocation'] = robotLocation update['location'] = [{ 'x': float(pt[0]) / w, 'y': float(pt[1]) / h } for pt in robotLocation] for i in [(1, 2), (2, 3), (3, 0)]: cv2.line(gray, robotLocation[i[0]], robotLocation[i[1]], 255, 3) # print(data) if len(data['updates']) > 0 and ws is not None: ws.send(json.dumps(data)) if SHOW_PREVIEW: # Display the resulting frame cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): # When everything done, release the capture cap.release() cv2.destroyAllWindows() import sys sys.exit()
# Save this file to Github as OpenCV-Track2colors.py import cv2 import numpy as np import random def nothing(): pass cv2.namedWindow('Trackbars') cv2.createTrackbar('HueLow', 'Trackbars', 24, 179, nothing) cv2.createTrackbar('HueHigh', 'Trackbars', 86, 179, nothing) cv2.createTrackbar('SatLow', 'Trackbars', 139, 255, nothing) cv2.createTrackbar('SatHigh', 'Trackbars', 255, 255, nothing) cv2.createTrackbar('ValLow', 'Trackbars', 122, 255, nothing) cv2.createTrackbar('ValHigh', 'Trackbars', 255, 255, nothing) ############################################## # Below lines are added for sencond color tracking cv2.namedWindow('Trackbars2') cv2.createTrackbar('HueLow2', 'Trackbars2', 24, 179, nothing) cv2.createTrackbar('HueHigh2', 'Trackbars2', 86, 179, nothing) cv2.createTrackbar('SatLow2', 'Trackbars2', 139, 255, nothing) cv2.createTrackbar('SatHigh2', 'Trackbars2', 255, 255, nothing) cv2.createTrackbar('ValLow2', 'Trackbars2', 122, 255, nothing) cv2.createTrackbar('ValHigh2', 'Trackbars2', 255, 255, nothing) ###############################################
class Cam(): points_graph = np.array([0,0,0]).reshape((3,1)) counter = 0 def nothing(): pass def quatToRot(self, q): sqw = q[3]*q[3] sqx = q[0]*q[0] sqy = q[1]*q[1] sqz = q[2]*q[2] # invs (inverse square length) is only required if quaternion is not already normalised invs = 1 / (sqx + sqy + sqz + sqw) m00 = ( sqx - sqy - sqz + sqw)*invs # since sqw + sqx + sqy + sqz =1/invs*invs m11 = (-sqx + sqy - sqz + sqw)*invs m22 = (-sqx - sqy + sqz + sqw)*invs tmp1 = q[0]*q[1] tmp2 = q[2]*q[3] m10 = 2.0 * (tmp1 + tmp2)*invs m01 = 2.0 * (tmp1 - tmp2)*invs tmp1 = q[0]*q[2] tmp2 = q[1]*q[3] m20 = 2.0 * (tmp1 - tmp2)*invs m02 = 2.0 * (tmp1 + tmp2)*invs tmp1 = q[1]*q[2] tmp2 = q[0]*q[3] m21 = 2.0 * (tmp1 + tmp2)*invs m12 = 2.0 * (tmp1 - tmp2)*invs R = np.matrix([[m00, m01, m02], [m10, m11, m12], [m20,m21,m22]]) return R def publish_3d_coords(self, left_max_x, left_max_y, right_max_x, right_max_y, imageSize): #monocular calibration 1 = left 2 = right CMatr1 = np.matrix([[2531.915668, 0.000000, 615.773452], [0.000000, 2594.436434, 344.505755], [0.000000, 0.000000, 1.000000]]).astype(np.float) pp = pprint.PrettyPrinter(indent=4) # print("CMatr1", CMatr1) #left distortion parameters: 1.281681 -15.773048 -0.010428 0.012822 0.000000 CMatr2 = np.matrix([[1539.714285, 0.000000, 837.703760], [0.000000, 1506.265655, 391.687374], [0.000000, 0.000000, 1.000000]]).astype(np.float) # print("CMatr2", CMatr2) projPoints1 = np.array([[left_max_x],[left_max_y]]).astype(np.float) projPoints2 = np.array([[right_max_x],[right_max_y]]).astype(np.float) distort_left = np.array([1.281681, -15.773048, -0.010428, 0.012822, 0.000000]).astype(np.float) distort_right = np.array([0.091411, -0.461269, 0.021006, 0.040117, 0.000000]).astype(np.float) # print("distort_left", distort_left) # print("distort_right", distort_right) RMat1 = self.quatToRot(np.array([-0.029, 0.992, -0.110, 0.053])) RMat2 = self.quatToRot(np.array([-0.019, 0.997, -0.038, -0.071])) RFinal = np.matmul(np.linalg.inv(RMat1),RMat2) T_left = np.array([-0.268, 0.516, 3.283]).astype(np.float) #--------------------CHANGE T_right = np.array([0.018, -0.184, 1.255]).astype(np.float) #--------------------CHANGE T_final = T_right - T_left #print("RFinal", RFinal) #print("T_final", T_final) #print(imageSize) R1,R2,P1,P2,Q, a,b = cv2.stereoRectify(CMatr1, distort_left, CMatr2, distort_right, (1280,720), RFinal, T_final, alpha=-1) #print("R1",R1) #print("R2",R2)CMatr1 #print("P1",P1) #print("P2",P2) #pnt1 = cv2.undistortPoints(projPoints1, CMatr1, distort_left, R=RMat1, P=P1) #pnt2 = cv2.undistortPoints(projPoints2, CMatr2, distort_right, R=RMat2, P=P2) #print("left:",projPoints1) #print("right:", projPoints2) P1_stereo = np.array([[4890.538324810042, 0.0, -1734.3179817199707, 0.0],[ 0.0, 4890.538324810042, 398.04181480407715, 0.0],[ 0.0, 0.0, 1.0, 0.0]]) P2_stereo = np.array([[4890.538324810042, 0.0, -1734.3179817199707, 8092.200252104331],[ 0.0, 4890.538324810042, 398.04181480407715, 0.0],[ 0.0, 0.0, 1.0, 0.0]]) points4D = cv2.triangulatePoints(P1_stereo, P2_stereo, projPoints1, projPoints2) #points3D = cv2.convertPointsFromHomogeneous(points4D) #print(points4D) #Converts 4D to 3D by [x,y,z,w] -> [x/w, y/w, z/w] points3D = np.array([ points4D[0]/points4D[3], points4D[1]/points4D[3], points4D[2]/points4D[3] ]) def run(self): points = [] global hue global sat global val cap0 = cv2.VideoCapture(0) cap1 = cv2.VideoCapture(1) while True: try: _,frame0 = cap0.read() _,frame1 = cap1.read() s = cv2.getTrackbarPos('Max Sat',objeto_string) if s == 0: s = global_max_sat lower = np.array([global_hue,global_sat,global_val]) upper = np.array([global_max_hue,s,global_max_value]) frame0_hsv = cv2.cvtColor(frame0,cv2.COLOR_BGR2HSV) frame0_hsv2 = frame0_hsv.copy() frame0_thresh = cv2.inRange(frame0_hsv,lower, upper) frame0_thresh = cv2.medianBlur(frame0_thresh,7) frame0_thresh2 = frame0_thresh.copy() frame0_inverted_image = cv2.bitwise_not(frame0_thresh2) frame0_kernel = np.ones((3,3),np.uint8) frame0_erosion = cv2.erode(frame0_inverted_image,frame0_kernel,iterations = 7) frame0_dilation = cv2.dilate(frame0_erosion,frame0_kernel,iterations = 15) frame0_edged = cv2.Canny(frame0_dilation, 30, 200) _,frame0_contours,_ = cv2.findContours(frame0_edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) maxArea = 0 max_x = None max_y = None max_w = 0 max_h = 0 for c in frame0_contours: frame0_x,frame0_y,frame0_w,frame0_h = cv2.boundingRect(c) area = frame0_w*frame0_h if area > maxArea: max_x = frame0_x max_y = frame0_y max_w = frame0_w max_h = frame0_h left_max_x = max_x left_max_y = max_y if (left_max_x == None or left_max_y == None): print("No ball") #TODO: Fix this to publish NaN or equivalent continue cv2.rectangle(frame0_dilation, (max_x, max_y), (max_x+max_w, max_y+max_h), (255, 0, 255), 2) cv2.imshow("camera 1", frame0_dilation) frame1_hsv = cv2.cvtColor(frame1,cv2.COLOR_BGR2HSV) frame1_hsv2 = frame1_hsv.copy() frame1_thresh = cv2.inRange(frame1_hsv,lower, upper) frame1_thresh = cv2.medianBlur(frame1_thresh,7) frame1_thresh2 = frame1_thresh.copy() frame1_inverted_image = cv2.bitwise_not(frame1_thresh2) frame1_kernel = np.ones((3,3),np.uint8) frame1_erosion = cv2.erode(frame1_inverted_image,frame1_kernel,iterations = 7) frame1_dilation = cv2.dilate(frame1_erosion,frame1_kernel,iterations = 15) frame1_edged = cv2.Canny(frame1_dilation, 30, 200) _, frame1_contours,_ = cv2.findContours(frame1_edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) maxArea = 0 max_x = None max_y = None max_w = 0 max_h = 0 for c in frame1_contours: frame1_x,frame1_y,frame1_w,frame1_h = cv2.boundingRect(c) area = frame1_w*frame1_h if area > maxArea: max_x = frame1_x max_y = frame1_y max_w = frame1_w max_h = frame1_h right_max_x = max_x right_max_y = max_y if (right_max_x == None or right_max_y == None): print("No ball") #TODO: Fix this to publish NaN or equivalent continue cv2.rectangle(frame1_dilation, (max_x, max_y), (max_x+max_w, max_y+max_h), (255, 0, 255), 2) cv2.imshow("camera 2", frame1_dilation) self.publish_3d_coords(left_max_x, left_max_y, right_max_x, right_max_y, frame1_dilation.shape[::-1]) if cv2.waitKey(1) ==1048603: exit(0) f.close() except ThreadError: self.thread_cancelled = True #plot the 3D points cv2.namedWindow(objeto_string) cv2.createTrackbar('Max Sat', objeto_string, global_sat, 255, nothing)
pass def update(): sigma = cv2.getTrackbarPos('sigma', 'control') * 2 + 1 str_sigma = cv2.getTrackbarPos('str_sigma', 'control') * 2 + 1 blend = cv2.getTrackbarPos('blend', 'control') / 10.0 print 'sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend) dst = coherence_filter(src, sigma=sigma, str_sigma=str_sigma, blend=blend) cv2.imshow('dst', dst) cv2.namedWindow('control', 0) cv2.createTrackbar('sigma', 'control', 9, 15, nothing) cv2.createTrackbar('blend', 'control', 7, 10, nothing) cv2.createTrackbar('str_sigma', 'control', 9, 15, nothing) print 'Press SPACE to update the image\n' cv2.imshow('src', src) update() while True: ch = 0xFF & cv2.waitKey() if ch == ord(' '): update() if ch == 27: break cv2.destroyAllWindows()
def store_images(g_id): total_pics = 150 pic_no = 0 cv2.namedWindow("Trackbars") cv2.createTrackbar('L - H', 'Trackbars', 0, 179, nothing) cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing) cv2.createTrackbar("L - V", "Trackbars", 0, 255, nothing) cv2.createTrackbar("U - H", "Trackbars", 179, 179, nothing) cv2.createTrackbar("U - S", "Trackbars", 255, 255, nothing) cv2.createTrackbar("U - V", "Trackbars", 255, 255, nothing) cv2.setTrackbarPos("L - H", "Trackbars", 0) cv2.setTrackbarPos('L - S', 'Trackbars', 40) cv2.setTrackbarPos('L - V', 'Trackbars', 46) create_folder("gestures/"+str(g_id)) while True: ret, frame = cam.read() frame = cv2.flip(frame,1) l_h = cv2.getTrackbarPos("L - H", "Trackbars") l_s = cv2.getTrackbarPos("L - S", "Trackbars") l_v = cv2.getTrackbarPos("L - V", "Trackbars") u_h = cv2.getTrackbarPos("U - H", "Trackbars") u_s = cv2.getTrackbarPos("U - S", "Trackbars") u_v = cv2.getTrackbarPos("U - V", "Trackbars") img = cv2.rectangle(frame, (425,100),(625,300), (0,255,0), thickness=2, lineType=8, shift=0) lower_blue = np.array([l_h, l_s, l_v]) upper_blue = np.array([u_h, u_s, u_v]) imcrop = img[100:300, 425:625] hsv = cv2.cvtColor(imcrop, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower_blue, upper_blue) # cv2.putText(frame, img_text, (30, 400), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0, 255, 0)) cv2.imshow("Trackbars", frame) cv2.imshow("mask", mask) if cv2.waitKey(1) & 0xFF == ord('s'): while True: ret, frame = cam.read() frame = cv2.flip(frame,1) l_h = cv2.getTrackbarPos("L - H", "Trackbars") l_s = cv2.getTrackbarPos("L - S", "Trackbars") l_v = cv2.getTrackbarPos("L - V", "Trackbars") u_h = cv2.getTrackbarPos("U - H", "Trackbars") u_s = cv2.getTrackbarPos("U - S", "Trackbars") u_v = cv2.getTrackbarPos("U - V", "Trackbars") img = cv2.rectangle(frame, (425,100),(625,300), (0,255,0), thickness=2, lineType=8, shift=0) lower_blue = np.array([l_h, l_s, l_v]) upper_blue = np.array([u_h, u_s, u_v]) imcrop = img[100:300, 425:625] hsv = cv2.cvtColor(imcrop, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower_blue, upper_blue) # cv2.putText(frame, img_text, (30, 400), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0, 255, 0)) cv2.imshow("Trackbars", frame) cv2.imshow("mask", mask) cv2.putText(frame, "Capturing...", (30, 60), cv2.FONT_HERSHEY_TRIPLEX, 2, (127, 255, 255)) cv2.imwrite("gestures/"+str(g_id)+"/"+str(pic_no)+".jpg", mask) pic_no+=1 print(pic_no) if pic_no == total_pics: cam.release() cv2.destroyAllWindows() # key = cv2.waitKey(1) if(cv2.waitKey(1) & 0xFF == ord('q')): cam.release() cv2.destroyAllWindows()
def main(): global frameContour global END global RGBLIST global RGB_Box global RGB_value END = 0 # Variable to END Camara once color has been seleceted frameWidth = 640 # Frame Width frameHeight = 480 # Frame Height cap = cv2.VideoCapture(0) # Intialize Webcam object ### use celphone camara via IP WebCam### use = input("Use Celphone Camara via IP WebCam? y/n ") if use == "y": address = "http://192.168.1.65:8080/video" # IP ADRESS FOR CELPHONE WEBCAM cap.open(address) # OPEN ADDRESS WITH cap object else: pass cap.set(3, frameWidth) # Set Frame Width cap.set(4, frameHeight) # Set Frame Height ### TRACKBAR ### cv2.namedWindow("Parameters") # Name window for parameters cv2.resizeWindow("Parameters", 640, 240) # Resize window cv2.createTrackbar("Threshold1", "Parameters", 45, 255, empty) # Threshold1 varaible for canny filter cv2.createTrackbar("Threshold2", "Parameters", 74, 255, empty) # Threshold2 varaible for canny filter cv2.createTrackbar("Area", "Parameters", 1000, 50000, empty) # Area to delete noise while True: # Iterate while True status, frame = cap.read() # Read Webcam if use == "y": frame = imutils.resize(frame, width=540) # Resize frame frameContour = frame.copy() # Make a copy of frame frameBlur = cv2.GaussianBlur( frame, (7, 7), 1) # Apply Gaussian Blur (this will reduce noise) frameGray = cv2.cvtColor( frameBlur, cv2.COLOR_BGR2GRAY) # Apply transformation from BGR TO GRAY ### GET TRACK VARAIABLES ### Threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters") Threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters") ### Apply filter ### frameCanny = cv2.Canny(frameGray, Threshold1, Threshold2) # Canny Filter ### Morphological operations ### kernel = np.ones((2, 2)) # Kernel for morhpological operations ### OPENING (EROSION FOLLOWED BY OPENING ) ### frameDilation = cv2.dilate(frameCanny, kernel, iterations=1) # Dilation getContours(frameDilation, frameContour) ### Stack frames and show tem Stack = stackImages( 0.8, ([frame, frameCanny], [frameDilation, frameContour])) cv2.imshow("Original", Stack) # Show frame cv2.setMouseCallback("Original", mousePoints) # Set callbak if cv2.waitKey(1) & 0xff == ord('q'): # q as waitkey break # break if usere presses q if END: sleep(10) print(RGBLIST) print(RGB_Box) print(RGB_value) plt.imshow(RGB_Box) plt.show() break cap.release() # Relase cap object cv2.destroyAllWindows() # Destroy Windows return RGBLIST
def make_show_sig(sig_file_name, lower_threshold=127, blur_amount=2, height=300, width=800): sig_name = sig_file_name.split('.')[0] global signature_org signature_org = cv2.imread(sig_file_name) if args.auto: binary_sig, trans_sig = make_sig(signature_org, lower_threshold, blur_amount, auto=1) cv2.imwrite(sig_name + '_binary.png', binary_sig) cv2.imwrite(sig_name + '_trans.png', trans_sig) return 0 should_crop = input( "\nWhat to crop the image before making signature ? [y/ any]:- " ).lower() if should_crop == 'y': global refPt, cropping refPt = [] cropping = False clone_signature = signature_org.copy() cv2.namedWindow('Original Image') cv2.imshow('Original Image', signature_org) cv2.setMouseCallback('Original Image', click_and_crop) print( 'Usage: press r to reset the crop area\n\t ' 'press c to crop (if you dont want to crop you can press c without selecting crop area or press x button)\n' 'Due to Open cv limitaions larger images are not displayed correctly. In that case you may need to crop image on other software' ) while cv2.getWindowProperty('Original Image', cv2.WND_PROP_VISIBLE): cv2.imshow('Original Image', signature_org) key = cv2.waitKey(1) & 0xFF # if the 'r' key is pressed, reset the cropping region if key == ord("r"): signature_org = clone_signature.copy() # if the 'c' key is pressed, break from the loop elif key == ord("c"): break if len(refPt) == 2: refPt = np.array(refPt) [y, y1], [x, x1] = [refPt[:, 1], refPt[:, 0]] signature_org = clone_signature[y:y1, x:x1] else: signature_org = clone_signature cv2.destroyAllWindows() prev_l_t, prev_b_a = (0, 0) cv2.namedWindow('Your Digital Signature', cv2.WINDOW_NORMAL) cv2.resizeWindow('Your Digital Signature', width, height) cv2.createTrackbar('lower_threshold', 'Your Digital Signature', 0, 255, lambda x: None) cv2.createTrackbar('blur_amount', 'Your Digital Signature', 0, 25, lambda x: None) cv2.setTrackbarPos('lower_threshold', 'Your Digital Signature', lower_threshold) cv2.setTrackbarPos('blur_amount', 'Your Digital Signature', blur_amount) while cv2.getWindowProperty('Your Digital Signature', cv2.WND_PROP_VISIBLE): l_t = cv2.getTrackbarPos('lower_threshold', 'Your Digital Signature') b_a = cv2.getTrackbarPos('blur_amount', 'Your Digital Signature') if (l_t != prev_l_t) or (b_a != prev_b_a): binary_sig, trans_sig = make_sig(signature_org, l_t, b_a) prev_l_t = l_t prev_b_a = b_a cv2.imshow("Your Digital Signature", trans_sig) key = cv2.waitKey(1) & 0xFF if key == ord('r'): cv2.setTrackbarPos('lower_threshold', 'Your Digital Signature', lower_threshold) cv2.setTrackbarPos('blur_amount', 'Your Digital Signature', blur_amount) if key == ord('s'): cv2.imwrite(sig_name + '_binary.png', binary_sig) cv2.imwrite(sig_name + '_trans.png', trans_sig) break elif key == ord('q'): break cv2.destroyAllWindows()