def cb_lambda(pos): # to avoid division by zero if pos==0: pos = 1; cv2.setTrackbarPos('Lambda*100', 'Filtered', np.int(pos)) update()
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
def process_frame(frame): """ Process frame based on user input """ channel = cv2.getTrackbarPos(tbar_channel_select_name, win_debug_name) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) frame = get_channel(frame, channel) block_size = cv2.getTrackbarPos(tbar_block_size_name, win_debug_name) threshold = cv2.getTrackbarPos(tbar_thresh_name, win_debug_name) if not block_size % 2 == 1: block_size += 1 cv2.setTrackbarPos(tbar_block_size_name, win_debug_name, block_size) if block_size <= 1: block_size = 3 cv2.setTrackbarPos(tbar_block_size_name, win_debug_name, block_size) adaptive = cv2.adaptiveThreshold(frame, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, block_size, threshold) if draw_contours: cframe = np.zeros((frame.shape[0], frame.shape[1], 3), np.uint8) contours, hierarchy = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(cframe, contours, -1, (255, 255, 255), 3) return cframe else: return adaptive
def syncTrackBars(self): '''record the position of openCV trackbars in lower and upper''' # make a copy for comparison later oldHSV = copy.deepcopy(self) #hue self.lower[0] = cv2.getTrackbarPos(self.sliderHue[0], self.controlWinName) self.upper[0] = cv2.getTrackbarPos(self.sliderHue[1],self.controlWinName) #saturation self.lower[1] = cv2.getTrackbarPos(self.sliderSat[0], self.controlWinName) # currently unused #self.upper[1] = cv2.getTrackbarPos(self.sliderSatat[1], self.controlWinName) #value self.lower[2] = cv2.getTrackbarPos(self.sliderVal[0], self.controlWinName) self.upper[2] = cv2.getTrackbarPos(self.sliderVal[1], self.controlWinName) #color range self.colorRange = cv2.getTrackbarPos(self.sliderColRange[0], self.controlWinName) # if the color range setting has changed, update the sliders if self.colorRange != oldHSV.colorRange: # use the new color range setting to update the hue values self.setRangeDefault() cv2.setTrackbarPos(color.sliderHue[0], color.controlWinName, color.defaultRanges[color.colorRange][0]) cv2.setTrackbarPos(color.sliderHue[1], color.controlWinName, color.defaultRanges[color.colorRange][1]) # look for changes in the Hue sliders and update the color pallet as needed if (self.lower[0] != oldHSV.lower[0]) or (self.upper[0] != oldHSV.upper[0]): # update the color swatches on the control panels self.update()
def set_power(self, power): self.power = power / 100.0 if self.power > 5.0: self.power = 5.0 if self.power < 2.5: self.power = 2.5 cv2.setTrackbarPos('Power', 'image', int(self.power * 100))
def showFrame(self, frame): # Make sure the requested frame is in bound: if frame < 0: frame = 0 elif frame >= self.videoFrames: frame = self.videoFrames - 1 # Do nothing if already shown: if self.currentFrame == frame: return # Seek frame (if not already there): if self.currentFrame + 1 != frame: self.file.seek(frame * self.frameSize, 0) # Read data: data = np.fromstring(self.file.read(self.frameSize), dtype=np.uint8) # Decode & show YUV: if (self.useYUV): # Split to channels: (Y1, Y2, UV) = np.split(data, 3) Y = np.concatenate((Y1, Y2)) (U, V) = np.split(UV, 2) # Re-arrange: Y = np.reshape(Y, (self.videoHeight, self.videoWidth)) U = np.repeat(U, 2, 0) U = np.reshape(U, (self.videoHeight / 2, self.videoWidth)) U = np.repeat(U, 2, 0) V = np.repeat(V, 2, 0) V = np.reshape(V, (self.videoHeight / 2, self.videoWidth)) V = np.repeat(V, 2, 0) # Stack & convert color: rgbFrame = cv2.cvtColor(np.dstack((Y,U,V)), cv2.COLOR_YUV2RGB) # Show image: cv2.imshow('Video', rgbFrame) # Decode & show RGB: else: # Stack & convert color: rgbFrame = np.reshape(data, (self.videoHeight, self.videoWidth, 3)) # Convert color: rgbFrame = cv2.cvtColor(rgbFrame, cv2.COLOR_RGB2BGR) # Show image: cv2.imshow('Video', rgbFrame) # Set current frame: self.currentFrame = frame # Set seek bar: cv2.setTrackbarPos("Seek", "Video", frame)
def get_frame(self, advance_frame=True): """Get a new frame from the video stream and return it""" if self.frame_skip > 0: self.set_frame(self.current_pos() + self.frame_skip) success, self.frame = self.capture.read() if not advance_frame: self.set_frame(self.current_pos() - 1) if success is False or self.frame is None: if self.loop_video: self.set_frame(0) while success is False or self.frame is None: success, self.frame = self.capture.read() else: self.stop() return None if self.resize_frame: self.frame = cv2.resize(self.frame, (self.resize_width, self.resize_height), interpolation=cv2.INTER_NEAREST) if self.current_pos() != self.frame_num: self.frame_num = self.current_pos() self.slider_num = int( self.frame_num * self.slider_ticks / self.video_len) cv2.setTrackbarPos(self.track_bar_name, self.video_name, self.slider_num) return self.frame
def show(self): ''' Shows all the windows with the right size and position Initiates the cam, etc. ''' cv2.resizeWindow("Settings", 1000, 450) cv2.moveWindow("Settings", 300, 540) cv2.resizeWindow("Results", 640, 480) cv2.moveWindow("Results", 0, 0) cv2.resizeWindow("Temp", 640, 480) cv2.moveWindow("Temp", 1030, 0) if self.mode == "cam": while True: key = cv2.waitKey(1) self.image = self.getVideoStreamCam() self.update() if key == 0: break else: cv2.setTrackbarPos("video_position", "Settings", 1) sliderValues = self.getSliderValues() self.image = self.getVideoFrame(sliderValues['video_position']) self.update() key = cv2.waitKey(0) cv2.destroyAllWindows()
def load_config(self, config): for color_name in HSV_NAMES: for bar_name in (MIN_BAR_NAME, MAX_BAR_NAME): section_name = '%s %s' % (self.window_name, bar_name) if config.has_option(section_name, color_name): bar_val = config.get(section_name, color_name) cv2.setTrackbarPos('%s %s' % (color_name, bar_name), self.window_name, int(bar_val))
def fn(x): if 'targetColor' in s and s['targetColor'] == x: return s['targetColor'] = x color = colors[x] cv2.setTrackbarPos('lowThresh', winName,s[color][0]) cv2.setTrackbarPos('highThresh',winName,s[color][1])
def obj(x): global f,obj_count,r1,b1,g1,r2,b2,g2,size if cv2.getTrackbarPos('object','toolbar')==1: f.write(str(obj_count)+','+str(r1)+','+str(b1)+','+str(g1)+','+str(r2)+','+str(b2)+','+str(g2)+','+str(size)+'\n') print 'object'+str(obj_count)+' is saved' obj_count = obj_count + 1 cv2.setTrackbarPos('object','toolbar',0)
def get_range(self): if self.switch_enabled: toggle_lower_upper = cv2.getTrackbarPos(MultiTrackbarWindow.switch, self.window_name) else: toggle_lower_upper = 0 if toggle_lower_upper == 0: if self.current_mode == 1: for trackbar in self.trackbars: cv2.setTrackbarPos(trackbar["name"], trackbar["window"], trackbar["current lower"]) self.current_mode = 0 for trackbar in self.trackbars: trackbar["current lower"] = cv2.getTrackbarPos(trackbar["name"], trackbar["window"]) else: if self.current_mode == 0: for trackbar in self.trackbars: cv2.setTrackbarPos(trackbar["name"], trackbar["window"], trackbar["current upper"]) self.current_mode = 1 for trackbar in self.trackbars: trackbar["current upper"] = cv2.getTrackbarPos(trackbar["name"], trackbar["window"]) if self.returns_unzipped_results: lower = (trackbar["current lower"] for trackbar in self.trackbars) upper = (trackbar["current upper"] for trackbar in self.trackbars) if not self.returns_generators: lower = tuple(lower) upper = tuple(upper) result = (lower, upper) else: result = ((trackbar["current lower"], trackbar["current upper"]) for trackbar in self.trackbars) if not self.returns_generators: result = tuple(result) return result
def set_center_x(self, x): half = self.config['width'] * self.power / 2 if x > self.cap_width - half - 1: x = self.cap_width - half - 1 if x < half: x = half self.center_x = int(x) cv2.setTrackbarPos('X', 'image', int(self.center_x))
def set_center_y(self, y): half = self.config['height'] * self.power / 2 if y > self.cap_height - half - 1: y = self.cap_height - half - 1 if y < half: y = half self.center_y = int(y) cv2.setTrackbarPos('Y', 'image', int(self.center_y))
def _stop_gui_tracking(self): """Run the code necessary to cleanup after tracking stopped.""" self._gui_sel = None self._gui_drag_start = None self.template_selection = None cv2.setTrackbarPos('Tracking', 'Controls', 0) self._gui_tracking = False self._gui_bead_pos = None
def create_all_trackbars(self, conf): if self.trackbarList: for item in self.trackbarList: self.create_trackbar(item[0], item[1]) # Init trackbar position from config # item[0] = "Brightness", item[2] = "brightness" cv2.setTrackbarPos(item[0], self.name, conf[item[2]]) self.win_set[item[2]] = conf[item[2]]
def apply_gray_change(cf, current_set, gray_max, sw, im_num): if gray_max != current_set[0]: save_config("scan", "gray_max", gray_max) cf["gray_max"] = gray_max if sw != current_set[1]: im_num = -1 cv2.setTrackbarPos('Restart', 'Laser Line', 0) return im_num
def View(self): global data, data2, tdata, tdata2, band begin = 0 num_data = 0 cv2.namedWindow('Result',cv2.CV_WINDOW_AUTOSIZE) cv2.createTrackbar('N_datos', 'Result', num_data, 60, self.update) cv2.createTrackbar('Begin', 'Result', begin, 60, self.update) self.img_temp = self.img.copy() predict = pd.Predictor() data = self.data[:] data2 = self.data[:] tdata = self.tpos[:] tdata2 = self.tpos[:] # TACKING w = len(self.points) for i in range(0,w-1): cv2.line(self.img, (self.points[i]),(self.points[i+1]),(255,0,0),1) w = len(self.data) for i in range(0,w-1): cv2.line(self.img, ((self.data[i][0],self.data[i][1])),((self.data[i+1][0],self.data[i+1][1])),(0,0,255),1) cv2.setTrackbarPos("N_datos","Result", self.n_data) while True: begin = cv2.getTrackbarPos('Begin','Result') + 90 num_data = cv2.getTrackbarPos('N_datos','Result') cv2.line(self.img_temp, (begin,0), (begin,240),(200,200,200),1) cv2.line(self.img_temp, (begin+num_data,0), (begin+num_data,240),(20,20,20),1) if band == False and num_data>2: predict.add_data(tdata2) predict.plot() band = True if len(predict.yAxis)>0: posH=begin for i in range(len(predict.yAxis)-1): posH=posH+1 try: if posH>(begin+num_data): cv2.line(self.img_temp,((posH,predict.yAxis[i])),((posH+1,predict.yAxis[i+1])),(255,0,0),1) else: cv2.line(self.img_temp,((posH,predict.yAxis[i])),((posH+1,predict.yAxis[i+1])),(0,255,255),1) except: pass cv2.imshow('Result',self.img_temp) k = cv2.waitKey(1) if k == 1048688: cv2.imwrite("image2.png",self.img_temp) if k == 1048603: self.end_cam() break
def updateTrackBars(self, winName, barDict): if isinstance(barDict, dict): for key in barDict: cv2.setTrackbarPos(key, winName, barDict[key]) #### Testing # self.syncTrackBars() self.updateControlWindow() # Testing #### else: pass
def update_trackbar(self): """ After loading a new configuration, update all trackbar positions """ try: for key, val in self.config.iteritems(): desc = self.var_to_description(key) val = self.get_value(val) cv2.setTrackbarPos(desc, self.winname, val) except: logging.exception("Filter: Error loading new configuration file.")
def changeCannyMin(x): global thresh, cannyMin, cannyMax cannyMin = x cannyMax = x + 50 #thresh = cv2.Canny(gray, cannyMin, cannyMax) cv2.setTrackbarMin('Umbral Maximo', 'ULA VISION 2016', cannyMin + 1) #cv2.setTrackbarMax('Canny Thresh Max', 'ULA VISION 2016', cannyMax) cv2.setTrackbarPos('Umbral Maximo', 'ULA VISION 2016', cannyMax) #thresh = cv2.threshold(blurred, cannyMin, cannyMax, cv2.THRESH_BINARY)[1] #cv2.imshow('ULA VISION 2016', thresh) process_image()
def mostrar_controles(self): #TODO: Poner nombre de ventana en variable #TODO: Escribir texto sobre imagen, avisando que es la imagen original #TODO: Agregar mas controles (ok, frame) = self.camara.read() brillo_actual = int(self.camara.get(cv2.CAP_PROP_BRIGHTNESS) * 100) cv2.imshow("Controles", frame) cv2.createTrackbar("Brillo", "Controles", 0, 100, self.establecer_brillo) cv2.setTrackbarPos("Brillo", "Controles", brillo_actual)
def __controle__(the_position, the_image, control_window_name): all_names = filter(lambda name: name.startswith(BLUR_PREFIX), globals()) for index, name in enumerate(all_names): window_name = name[len(BLUR_PREFIX):] method = globals()[name] cv2.setTrackbarPos('blur', window_name, the_position) refresh_image(the_position, the_image, window_name, method) point_value = get_odd_value(the_position) draw_text(the_image, 'blurring value: '+str(point_value)) cv2.imshow(control_window_name, the_image)
def __controle__(the_position, the_image, control_window_name): kernel_size_value = cv2.getTrackbarPos(TRACKBAR_1, control_window_name) all_names = filter(lambda name: name.startswith(PERFORM_PREFIX), globals()) for index, name in enumerate(all_names): window_name = name[len(PERFORM_PREFIX):] method = globals()[name] cv2.setTrackbarPos(TRACKBAR_1, window_name, kernel_size_value) refresh_image(the_position, the_image, window_name, method) cv2.imshow(control_window_name, the_image)
def _add_to_window(self): # Empty call back for trackbars def nothing(x): pass # create trackbars for color range for color_name, max_value in zip(HSV_NAMES, HSV_MAX_VALS): cv2.createTrackbar('%s %s' % (color_name, MIN_BAR_NAME), self.window_name, 0, max_value, nothing) cv2.createTrackbar('%s %s' % (color_name, MAX_BAR_NAME), self.window_name, 0, max_value, nothing) cv2.setTrackbarPos('%s %s' % (color_name, MAX_BAR_NAME), self.window_name, max_value) cv2.createTrackbar('Enabled', self.window_name, 0, 1, nothing)
def _propagate_settings(self): for key in [ "Hhigh", "Hlow", "Shigh", "Slow", "Vhigh", "Vlow", "left", "top", "width", "height", "cH", "blur", ]: value = getattr(self.settings, key) cv2.setTrackbarPos(key, WINDOWNAME, value) for key in ["cmix"]: value = getattr(self.settings, key) cv2.setTrackbarPos(key, WINDOWNAME, int(value * 1000))
def getFrame(self, readNextFrame=True): """ A method to be used inside of a while loop. Reads frames from a video or a live capture. :param readNextFrame: True by default. Use to refresh the capture's current frame without proceeding to the next :return: A numpy array containg the frame captured (shape = (height, width, 3)) """ if self.isRunning is False: self.stopCamera() return if readNextFrame is False: self.decrementFrame() if self.frameSkip > 0: if type(self.camSource) == str: current = self.camera.get(cv2.CAP_PROP_POS_FRAMES) self.camera.set(cv2.CAP_PROP_POS_FRAMES, current + self.frameSkip) success, self.frame = self.camera.read() if success is False or self.frame is None: if type(self.camSource) == int: raise Exception("Failed to read from camera!") elif self.loopVideo == True: self.setFrame(0) while success is False or self.frame is None: success, self.frame = self.camera.read() else: self.stopCamera() if not self.quitOnEnd: return None # it's a video. stop the loop else: print("Quitting...") quit() if type(self.camSource) == str: if self.frame.shape[0:2] != (self.height, self.width): self.frame = cv2.resize(self.frame, (self.width, self.height), interpolation=cv2.INTER_NEAREST) cv2.setTrackbarPos(self.trackbarName, self.windowName, int(self.camera.get( cv2.CAP_PROP_POS_FRAMES))) if self.dimensions is not None: x0, y0, x1, y1 = self.dimensions self.frame = self.frame[y0:y1, x0:x1] return self.frame
def initializeParticleSlider(pf, name, particleCount = 10, sigmaSpeed=6, sigmaSize=6, probLambda=15): def setParticleCount(x): if x > 5: pf.count = x def setSigmaSpeed(x): if x > 0: pf.SIGMA_velocity = x / 10. def setSigmaSize(x): if x > 0: pf.SIGMA_size = x / 100. def setProbLambda(x): if x > 0: pf.probLambda = x cv2.createTrackbar("Num particles", name, 5, 2000, setParticleCount) cv2.setTrackbarPos("Num particles", name, pf.count) cv2.createTrackbar("Sigma speed / 10", name, 1, 200, setSigmaSpeed) cv2.setTrackbarPos("Sigma speed / 10", name, int(pf.SIGMA_velocity)*10) cv2.createTrackbar("Sigma size / 100", name, 0, 100, setSigmaSize) cv2.setTrackbarPos("Sigma size / 100", name, int(pf.SIGMA_size*100)) cv2.createTrackbar("Probability lambda", name, 1, 100, setProbLambda) cv2.setTrackbarPos("Probability lambda", name, pf.probLambda)
def import_from_config_file(self): target_code_def = np.array([0.8,0.91,0.76,0.84,0.7,0.66,0.49]) raw_ratio = sc_config.config.get_array('algorithm', 'target_code',target_code_def) for i in range(0,len(self.ratio)): #update buffer if(i < len(raw_ratio)): self.ratio[i]= raw_ratio[i] else: self.ratio[i] = 0 #update trackbars field = 'Ratio ' + str(i) cv2.setTrackbarPos(field,'parameters',int(self.ratio[i] * 100))
def _create_gui(self): """Initialises the things needed for the GUI.""" # Create the necessary GUI elements cv2.namedWindow('Preview', cv2.WINDOW_AUTOSIZE) cv2.namedWindow('Controls', cv2.WINDOW_AUTOSIZE) cv2.createTrackbar('Greyscale', 'Controls', 0, 1, self._gui_nothing) cv2.createTrackbar('Tracking', 'Controls', 0, 1, self._gui_nothing) # Set default values cv2.setTrackbarPos('Greyscale', 'Controls', 1) cv2.setTrackbarPos('Tracking', 'Controls', 0) # Add mouse functionality on image click: cv2.setMouseCallback('Preview', self._on_gui_mouse) # For the sake of speed, use the RPi iterator: self.camera.use_iterator(True)
def pick_color(event, x, y, flags, params): """ Calculates HSV value from click and sets it to trackbars """ frame, frame_HSV, stack, frameStack = params # Check if event was a mouse left click if event == cv2.EVENT_LBUTTONDOWN: # Transforms x and y coordinates of frameStack to original frame in upper left part of stack x = int(x * (frame.shape[1] / (frameStack.shape[1] / np.shape(stack)[1]))) y = int(y * (frame.shape[0] / (frameStack.shape[0] / np.shape(stack)[0]))) # Checks if x and y coordinates are inside the upper left frame if x <= frame.shape[1] and y <= frame.shape[0]: # Gets HSV values for pixel clicked pixel = frame_HSV[y, x] # HUE, SATURATION, AND VALUE (BRIGHTNESS) RANGES. TOLERANCE COULD BE ADJUSTED. # Set range = 0 for hue and range = 1 for saturation and brightness # set upper_or_lower = 1 for upper and upper_or_lower = 0 for lower hue_lower = check_boundaries(pixel[0], 9, 0, 0) hue_upper = check_boundaries(pixel[0], 9, 0, 1) sat_lower = check_boundaries(pixel[1], 83, 1, 0) sat_upper = check_boundaries(pixel[1], 83, 1, 1) val_lower = check_boundaries(pixel[2], 100, 1, 0) val_upper = check_boundaries(pixel[2], 100, 1, 1) # Change trackbar position value to clicked one with tolerance cv2.setTrackbarPos('Hue Min', 'Color Calibration', hue_lower) cv2.setTrackbarPos('Hue Max', 'Color Calibration', hue_upper) cv2.setTrackbarPos('Sat Min', 'Color Calibration', sat_lower) cv2.setTrackbarPos('Sat Max', 'Color Calibration', sat_upper) cv2.setTrackbarPos('Val Min', 'Color Calibration', val_lower) cv2.setTrackbarPos('Val Max', 'Color Calibration', val_upper)
# Load in image image = cv2.imread('r1.png') # Create a window cv2.namedWindow('image') # create trackbars for color change cv2.createTrackbar('HMin','image',0,179,nothing) # Hue is from 0-179 for Opencv cv2.createTrackbar('SMin','image',0,255,nothing) cv2.createTrackbar('VMin','image',0,255,nothing) cv2.createTrackbar('HMax','image',0,179,nothing) cv2.createTrackbar('SMax','image',0,255,nothing) cv2.createTrackbar('VMax','image',0,255,nothing) # Set default value for MAX HSV trackbars. cv2.setTrackbarPos('HMax', 'image', 179) cv2.setTrackbarPos('SMax', 'image', 255) cv2.setTrackbarPos('VMax', 'image', 255) # Initialize to check if HSV min/max value changes hMin = sMin = vMin = hMax = sMax = vMax = 0 phMin = psMin = pvMin = phMax = psMax = pvMax = 0 output = image wait_time = 33 while(1): # get current positions of all trackbars hMin = cv2.getTrackbarPos('HMin','image') sMin = cv2.getTrackbarPos('SMin','image')
def open_video(): cap = cv.VideoCapture(0) global data_to_print data_to_print = "" pts = collections.deque() def nothing(x): pass def safe_div(x, y): if y == 0: return 0 return x / y barsWindow = 'Bars' hl = 'Hue Low' hh = 'Hue High' sl = 'Saturation Low' sh = 'Saturation High' vl = 'Value Low' vh = 'Value High' cv.namedWindow(barsWindow, flags=cv.WINDOW_AUTOSIZE) cv.createTrackbar(hl, barsWindow, 0, 179, nothing) cv.createTrackbar(hh, barsWindow, 0, 179, nothing) cv.createTrackbar(sl, barsWindow, 0, 255, nothing) cv.createTrackbar(sh, barsWindow, 0, 255, nothing) cv.createTrackbar(vl, barsWindow, 0, 255, nothing) cv.createTrackbar(vh, barsWindow, 0, 255, nothing) cv.setTrackbarPos(hl, barsWindow, 0) cv.setTrackbarPos(hh, barsWindow, 179) cv.setTrackbarPos(sl, barsWindow, 0) cv.setTrackbarPos(sh, barsWindow, 255) cv.setTrackbarPos(vl, barsWindow, 0) cv.setTrackbarPos(vh, barsWindow, 255) while True: x, frame = cap.read() if cv.waitKey(5) & 0xFF == ord('q'): break frame = imutils.resize(frame, width=600) hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) hul = cv.getTrackbarPos(hl, barsWindow) huh = cv.getTrackbarPos(hh, barsWindow) sal = cv.getTrackbarPos(sl, barsWindow) sah = cv.getTrackbarPos(sh, barsWindow) val = cv.getTrackbarPos(vl, barsWindow) vah = cv.getTrackbarPos(vh, barsWindow) colorLower = np.array([hul, sal, val]) colorUpper = np.array([huh, sah, vah]) #colorLower = (24, 100, 100) #colorUpper = (44, 255, 255) mask = cv.inRange(hsv, colorLower, colorUpper) mask = cv.erode(mask, None, iterations=2) mask = cv.dilate(mask, None, iterations=2) cnts = cv.findContours(mask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)[-2] print(cnts) if len(cnts) > 0: c = max(cnts, key=cv.contourArea) rect = cv.minAreaRect(c) box = cv.boxPoints(rect) box = np.int0(box) (tl, tr, br, bl) = box def midpoint(ptA, ptB): return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5) (tltrX, tltrY) = midpoint(tl, tr) (blbrX, blbrY) = midpoint(bl, br) (tlblX, tlblY) = midpoint(tl, bl) (trbrX, trbrY) = midpoint(tr, br) dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY)) dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY)) pixelsPerMetric = 1 dimA = dA / pixelsPerMetric dimB = dB / pixelsPerMetric cv.putText(frame, "{:.1f}mm".format(dimA), (int(tltrX - 15), int(tltrY - 10)), cv.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2) cv.putText(frame, "{:.1f}mm".format(dimB), (int(trbrX + 10), int(trbrY)), cv.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2) global length global breadth length = "{:.1f}mm".format(dimA) breadth = "{:.1f}mm".format(dimB) M = cv.moments(c) print(M) cX = int(safe_div(M["m10"], M["m00"])) cY = int(safe_div(M["m01"], M["m00"])) global area area = "{:.1f}mm".format(M["m00"]) pts.appendleft((cX, cY)) for i in range(1, len(pts)): if pts[i - 1] is None or pts[i] is None: continue cv.line(frame, pts[i - 1], pts[i], (0, 0, 255), 3) cv.drawContours(frame, [box], 0, (123, 200, 255), 2) cv.circle(frame, (cX, cY), 5, (255, 255, 255), -1) cv.imshow('frame', frame)
def nothing(x): pass alpha = 0.0 cap1 = cv2.VideoCapture(0) cap2 = cv2.VideoCapture(1) cap1.set(3, 480) cap1.set(4, 640) cap2.set(3, 480) cap2.set(4, 640) cv2.namedWindow('alpha') cv2.createTrackbar('a', 'alpha', 0, 100, nothing) cv2.setTrackbarPos('a', 'alpha', 50) while True: _, img1 = cap1.read() _, img2 = cap2.read() gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) alpha = cv2.getTrackbarPos('a', 'alpha') alpha /= 100 beta = 1.0 - alpha blend = cv2.addWeighted(gray1, alpha, gray2, beta, 0.0) blurred = cv2.GaussianBlur(blend, (5, 5), 0) ret, thresh = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY) ''' contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#create window img = np.zeros((N, N, 3), np.uint8) img2 = np.zeros((N, N, 3), np.uint8) cv.namedWindow('image') cv.createTrackbar('u', 'image', 0, G_MAX - 1, nothing) while (1): final_image = np.hstack((img, img2)) cv.imshow('image', final_image) k = cv.waitKey(1) & 0xFF if k == 27: break #create track bar for u value u = cv.getTrackbarPos('u', 'image') if first_run: cv.setTrackbarPos('u', 'image', 131) first_run = False if u != prev_u: #if u is different to prev u create a black image img = np.zeros((N, N, 3), np.uint8) img2 = np.zeros((N, N, 3), np.uint8) for h in range(0, H_MAX): for s in range(0, G_MAX): #calculate x and y x = int(s * (np.cos(np.deg2rad(h / 10)))) y = int(s * (np.sin(np.deg2rad(h / 10)))) #get nearby rgb values r = u + x / np.sqrt(2) + y / np.sqrt(6) g = u - 2 * y / np.sqrt(6) b = u - x / np.sqrt(2) + y / np.sqrt(6)
def loadDefault(): cv.setTrackbarPos(v_min_text, settings_window, 0) cv.setTrackbarPos(v_max_text, settings_window, 255) cv.setTrackbarPos(k_size_text, settings_window, 5) cv.setTrackbarPos(red_text, settings_window, 1) cv.setTrackbarPos(blue_text, settings_window, 1) cv.setTrackbarPos(green_text, settings_window, 1) cv.setTrackbarPos(min_s_text, settings_window, 1) cv.setTrackbarPos(max_s_text, settings_window, 100) cv.setTrackbarPos(deviation_text, settings_window, 100) cv.setTrackbarPos(origin_text, settings_window, 0) cv.setTrackbarPos(thresh_text, settings_window, 0) cv.setTrackbarPos(contours_text, settings_window, 0) cv.setTrackbarPos(ktype_text, settings_window, SQUARE)
def run(self): """Start the GUI.""" cv2.namedWindow(self.window) cv2.namedWindow('Result') cv2.createTrackbar('Axis', self.window, 0, 1, self.process) cv2.createTrackbar('Origin_Vert', self.window, 0, 1, self.process) cv2.createTrackbar('Origin_Horiz', self.window, 0, 1, self.process) cv2.createTrackbar('Object Separation', self.window, 1, 1000, self.process) cv2.createTrackbar('Camera X Offset', self.window, 0, 1000, self.process) cv2.createTrackbar('Camera Y Offset', self.window, 0, 1000, self.process) cv2.createTrackbar('Calibration Iterations', self.window, 1, 10, self.process) # cv2.createTrackbar( # 'Scale * 1000', self.window, 0, 10000, self.process) cv2.setTrackbarPos('Axis', self.window, 1) cv2.setTrackbarPos('Origin_Vert', self.window, 1) cv2.setTrackbarPos('Origin_Horiz', self.window, 0) cv2.setTrackbarPos('Object Separation', self.window, 100) cv2.setTrackbarPos('Camera X Offset', self.window, 50) cv2.setTrackbarPos('Camera Y Offset', self.window, 100) cv2.setTrackbarPos('Calibration Iterations', self.window, 3) # cv2.setTrackbarPos('Scale * 1000', self.window, 0) while True: k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows()
def on_low_H_thresh_trackbar(val): global low_H global high_H low_H = val low_H = min(high_H - 1, low_H) cv.setTrackbarPos(low_H_name, window_detection_name, low_H)
def visualize_results(self): # initialize the self.IMAGE_PATH_LIST, self.LAST_IMAGE_INDEX # self.load_image_sequence(self.active_directory) self.load_active_directory() # this function must be after self.load_image_sequence(), otherwise, the trackBar # for image list can not be initialized (as number of image not known) self.init_image_window_and_mouse_listener() # load the first image in the IMAGE_PATH_LIST, # initilize self.active_image_index and related information for the active image self.set_image_index(0) while True: # copy the current image tmp_img = self.active_image.copy() # get annotation paths image_path = self.IMAGE_PATH_LIST[self.active_image_index] # image_path is not a global variable self.active_image_annotation_path = self.get_annotation_path(image_path) # print('annotation_path=', annotation_path) # display annotated bboxes self.draw_bboxes_from_file(tmp_img, self.active_image_annotation_path) # , image_width, image_height self.set_active_bbox_idx_if_NONE() # set the active directory based on mouse cursor # self.set_active_bbox_idx_based_on_mouse_position() self.draw_active_bbox(tmp_img) cv2.imshow(self.IMAGE_WINDOW_NAME, tmp_img) ''' Key Listeners START ''' pressed_key = self.read_pressed_key() # 255 Linux or Windows, cv2.waitKeyEx() & 0xFF , -1 # Windows cv2.waitKeyEx() or Linux cv2.waitKey(), 0 # Windows cv2.waitKey() if pressed_key != 255 and pressed_key != 0 and pressed_key != -1: # print('pressed_key=', pressed_key) # ('pressed_key=', -1) if no key is pressed. # print('pressed_key & 0xFF =', pressed_key & 0xFF) # print('self.platform = ', self.platform) # handle string key a -z if ord('a') <= pressed_key <= ord('z'): # 'a': 97, 'z': 122 if pressed_key == ord('a') or pressed_key == ord('d'): # show previous image key listener if pressed_key == ord('a'): self.active_image_index = decrease_index( self.active_image_index, self.LAST_IMAGE_INDEX ) # show next image key listener elif pressed_key == ord('d'): self.active_image_index = increase_index( self.active_image_index, self.LAST_IMAGE_INDEX ) cv2.setTrackbarPos( self.TRACKBAR_IMG, self.IMAGE_WINDOW_NAME, self.active_image_index ) elif pressed_key & 0xFF == 27: # Esc key is pressed # close the window cv2.destroyWindow(self.IMAGE_WINDOW_NAME) break if self.WITH_QT: # if window gets closed then quit if cv2.getWindowProperty(self.IMAGE_WINDOW_NAME, cv2.WND_PROP_VISIBLE) < 1: # close the window cv2.destroyWindow(self.IMAGE_WINDOW_NAME) break
def on_low_S_thresh_trackbar(val): global low_S global high_S low_S = val low_S = min(high_S - 1, low_S) cv.setTrackbarPos(low_S_name, window_detection_name, low_S)
def on_high_H_thresh_trackbar(val): global low_H global high_H high_H = val high_H = max(high_H, low_H + 1) cv.setTrackbarPos(high_H_name, window_detection_name, high_H)
def on_high_S_thresh_trackbar(val): global low_S global high_S high_S = val high_S = max(high_S, low_S + 1) cv.setTrackbarPos(high_S_name, window_detection_name, high_S)
def on_low_V_thresh_trackbar(val): global low_V global high_V low_V = val low_V = min(high_V - 1, low_V) cv.setTrackbarPos(low_V_name, window_detection_name, low_V)
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)
pass #First argument is just the file name of whatever you're trying to calibrate. image = cv2.imread(sys.argv[1]) sliderWindow = 'Sliders' cv2.namedWindow(sliderWindow) imageHSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #cv2.imshow("test", imageHSV) wnd = "Calibration" cv2.createTrackbar('H_low',sliderWindow,0,179,nothing) cv2.createTrackbar('S_low',sliderWindow,0,255,nothing) cv2.createTrackbar('V_low',sliderWindow,0,255,nothing) cv2.createTrackbar('H_high',sliderWindow,0,179,nothing) cv2.createTrackbar('S_high',sliderWindow,0,255,nothing) cv2.createTrackbar('V_high',sliderWindow,0,255,nothing) cv2.setTrackbarPos('H_low', sliderWindow, 0) cv2.setTrackbarPos('H_high', sliderWindow, 20) cv2.setTrackbarPos('S_low', sliderWindow, 100) cv2.setTrackbarPos('S_high', sliderWindow, 255) cv2.setTrackbarPos('V_low', sliderWindow, 100) cv2.setTrackbarPos('V_high', sliderWindow, 255) r = 1000.0 / image.shape[1] dim = (1000, int(image.shape[0] * r)) while(1): hueLow = cv2.getTrackbarPos('H_low', sliderWindow) hueHigh = cv2.getTrackbarPos('H_high', sliderWindow) satLow = cv2.getTrackbarPos('S_low', sliderWindow) satHigh = cv2.getTrackbarPos('S_high', sliderWindow) valLow = cv2.getTrackbarPos('V_low', sliderWindow) valHigh = cv2.getTrackbarPos('V_high', sliderWindow) imgCopy = imageHSV
pass impath = ("/home/mohsencactus/python 2/Begin/2skele.jpg") img = cv.imread(impath) skelet = np.copy(img) hsv = cv.cvtColor(skelet,cv.COLOR_BGR2HSV) cv.namedWindow("window2",cv.WINDOW_NORMAL) cv.createTrackbar("Hmin","window2",0,255,nthn) cv.createTrackbar("Hmax","window2",0,180,nthn) cv.createTrackbar("Smin","window2",0,255,nthn) cv.createTrackbar("Smax","window2",0,255,nthn) cv.createTrackbar("Vmin","window2",0,255,nthn) cv.createTrackbar("Vmax","window2",0,255,nthn) cv.setTrackbarPos("Hmax","window2",180) cv.setTrackbarPos("Smax","window2",255) cv.setTrackbarPos("Vmax","window2",255) while True: Hmin = cv.getTrackbarPos("Hmin","window2") Smin = cv.getTrackbarPos("Smin","window2") Vmin = cv.getTrackbarPos("Vmin","window2") Hmax = cv.getTrackbarPos("Hmax","window2") Smax = cv.getTrackbarPos("Smax","window2") Vmax = cv.getTrackbarPos("Vmax","window2") mins = np.array([Hmin,Smin,Vmin]) maxs = np.array([Hmax,Smax,Vmax]) binaried = cv.inRange(hsv,mins,maxs) filtered = cv.bitwise_and(skelet,skelet,mask = binaried)
def setDefaultPosition(self): ratio = (self.defaultValue - self.desiredStart) / (self.desiredEnd - self.desiredStart) defaultPosition = ratio * (self.end - self.start) + self.start cv2.setTrackbarPos(self.description, self.windowName, int(defaultPosition))
def loadMeta(settings_file): with open(settings_file) as f: loaded = json.load(f) cv.setTrackbarPos(v_min_text, settings_window, loaded[json_minV]) cv.setTrackbarPos(v_max_text, settings_window, loaded[json_maxV]) cv.setTrackbarPos(k_size_text, settings_window, loaded[json_ksize]) cv.setTrackbarPos(red_text, settings_window, loaded[json_showR]) cv.setTrackbarPos(blue_text, settings_window, loaded[json_showB]) cv.setTrackbarPos(green_text, settings_window, loaded[json_showG]) cv.setTrackbarPos(min_s_text, settings_window, loaded[json_min_s]) cv.setTrackbarPos(max_s_text, settings_window, loaded[json_max_s]) cv.setTrackbarPos(deviation_text, settings_window, loaded[json_deviation]) cv.setTrackbarPos(origin_text, settings_window, loaded[json_origin]) cv.setTrackbarPos(thresh_text, settings_window, loaded[json_thresh]) cv.setTrackbarPos(contours_text, settings_window, loaded[json_contours]) cv.setTrackbarPos(ktype_text, settings_window, loaded[json_ktype])
if WITH_QT: cv2.displayOverlay(WINDOW_NAME, "Selected label: " + class_list[class_index] + "" "\nPress [w] or [s] to change.", 120) cv2.imshow(WINDOW_NAME, tmp_img) pressed_key = cv2.waitKey(50) """ Key Listeners START """ if pressed_key == ord('a') or pressed_key == ord('d'): # show previous image key listener if pressed_key == ord('a'): img_index = decrease_index(img_index, last_img_index) # show next image key listener elif pressed_key == ord('d'): img_index = increase_index(img_index, last_img_index) cv2.setTrackbarPos(TRACKBAR_IMG, WINDOW_NAME, img_index) elif pressed_key == ord('s') or pressed_key == ord('w'): # change down current class key listener if pressed_key == ord('s'): class_index = decrease_index(class_index, last_class_index) # change up current class key listener elif pressed_key == ord('w'): class_index = increase_index(class_index, last_class_index) color = class_rgb[class_index].tolist() draw_line(tmp_img, mouse_x, mouse_y, height, width, color) cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) #REMOVING BAD DATA elif pressed_key == ord('r'):
def checkRecord(request, video_id): videoID = video_id record = Record.objects.filter(id=videoID).first() videoURL = record.record_url def on_change(x): # 设置播放的帧数 cap.set(cv2.CAP_PROP_POS_FRAMES, x) # 调用摄像头 cap = cv2.VideoCapture( '../../Envs/virtual_env/Lib/site-packages/simpleui/{}'.format( videoURL)) cv2.namedWindow("frame", cv2.WINDOW_AUTOSIZE) frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) cv2.createTrackbar("Frame", "frame", 0, int(frame_count), on_change) # 定义HOG对象,采用默认参数,或者按照下面的格式自己设置 defaultHog = cv2.HOGDescriptor() # 设置SVM分类器,用默认分类器 defaultHog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) c = 2 timeF = 3 while 1: framePos = cap.get(cv2.CAP_PROP_POS_FRAMES) cv2.setTrackbarPos("Frame", "frame", int(framePos)) ret, frame = cap.read() img = frame (h, w) = img.shape[:2] width = 900 r = width / float(w) dim = (width, int(h * r)) if ret: # 获取摄像头拍摄到的画面 if (c % timeF == 0): # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) (peoples, weights) = defaultHog.detectMultiScale(img, winStride=(4, 4), padding=(8, 8), scale=1.4) # peoples = np.array([[x, y, x + w, y + h] for (x, y, w, h) in peoples]) # pick = non_max_suppression(peoples, probs=None, overlapThresh=0.65) for (x, y, w, h) in peoples: img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # print(type(peoples)) num_p = len(peoples) # print(num_p) txt = 'Current have peoples:{}\nq:quit the frame'.format( str(num_p)) y, dy = 0, 20 for i, line in enumerate(txt.split('\n')): y += dy cv2.putText(img, line, (10, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 0), 2) # 实时展示效果画面 cv2.imshow('frame', img) # 每5毫秒监听一次键盘动作 if cv2.waitKey(50) & 0xFF == ord('q'): break c += 1 # print(c) else: break cv2.destroyAllWindows() cap.release() return JsonResponse({"res": "调用成功"})
def adjust_exposure_time(self): cv.namedWindow('PID Tuning') cv.createTrackbar('KP','PID Tuning',0,255,self.nothing) cv.createTrackbar('KI','PID Tuning',0,255,self.nothing) cv.createTrackbar('KD','PID Tuning',0,255,self.nothing) cv.setTrackbarPos('KP','PID Tuning',0) cv.setTrackbarPos('KI','PID Tuning',0) cv.setTrackbarPos('KD','PID Tuning',0) r = rospy.Rate(15) while not rospy.is_shutdown(): if self.hsv is None: print_result('image is none') continue h, s, v = cv.split(self.hsv) v_one_d = v.ravel() v_mode = self.get_mode(v_one_d) ev = self.get_param('exposure') print_result('Real Exposure Value') print_result(ev) ############# DISPLAY ############# cv.imshow('PID Tuning', self.image) cv.waitKey(1) plt.hist(v_one_d, 256, [0, 256]) plt.pause(0.001) plt.cla() ################################### if ev is None: print_result('EV is None') continue KP = cv.getTrackbarPos('KP','PID Tuning') KI = cv.getTrackbarPos('KI','PID Tuning') KD = cv.getTrackbarPos('KD','PID Tuning') self.KP = KP / 100. self.KI = KI / 100. # self.KI = 0 self.KD = KD / 100. ############# PID ############# self.err = self.expected_v - v_mode self.sum_err += ((self.err + self.previous_err) / 2 )* 0.5 self.diff_err = (self.err - self.previous_err) / 0.5 print('KP:', self.KP) print('KI:', self.KI) print('KD:', self.KD) print('ERR:', self.err) print('PRV_ERR:', self.previous_err) print('SUM_ERR:', self.sum_err) ev += (self.KP * self.err) + (self.KI * self.sum_err) + (self.KD * self.diff_err) self.previous_err = self.err ################################### print_result('Exposure') print_result(ev) print_result('V mode') print_result(v_mode) self.set_param('exposure', ev) print('EV: ',ev) rospy.sleep(0.5)
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') vMin = cv2.getTrackbarPos('V min', 'HSV') vMax = cv2.getTrackbarPos('V max', 'HSV')
'r') infile.close() index += 1 except FileNotFoundError: pass filename = params_filename + index.__str__() + params_ext outfile = open(filename, 'w') json.dump(track_params.to_dict(), outfile, sort_keys=True, indent=4) outfile.close() print('saved to: ' + filename) elif in_read == ord('r'): cv2.setTrackbarPos('hue min', 'bars', 0) cv2.setTrackbarPos('hue max', 'bars', 255) cv2.setTrackbarPos('saturation min', 'bars', 0) cv2.setTrackbarPos('saturation max', 'bars', 255) cv2.setTrackbarPos('value min', 'bars', 0) cv2.setTrackbarPos('value max', 'bars', 255) cv2.setTrackbarPos('kernel size', 'bars', 7) elif in_read == ord('q'): cv2.destroyAllWindows() break myCamera.release() elif u_flag is not None: # Undistort a single image infile = cv2.imread(image_filename + '0' + image_ext) output = undistort(infile, np.array(camera_config.camera_matrix),
img = np.zeros((ht, wd, 3), np.uint8) cv2.namedWindow('image') #make trackbars for upper / lower ranges #lower range cv2.createTrackbar('H lower', 'image', 0, 179, nothing) cv2.createTrackbar('S lower', 'image', 0, 255, nothing) cv2.createTrackbar('V lower', 'image', 0, 255, nothing) #upper range cv2.createTrackbar('H upper', 'image', 0, 179, nothing) cv2.createTrackbar('S upper', 'image', 0, 255, nothing) cv2.createTrackbar('V upper', 'image', 0, 255, nothing) # #initialize trackbar positions ini = [0, 0, 0, 179, 255, 255] # orange balloon cv2.setTrackbarPos('H lower', 'image', ini[0]) cv2.setTrackbarPos('S lower', 'image', ini[1]) cv2.setTrackbarPos('V lower', 'image', ini[2]) cv2.setTrackbarPos('H upper', 'image', ini[3]) cv2.setTrackbarPos('S upper', 'image', ini[4]) cv2.setTrackbarPos('V upper', 'image', ini[5]) # set color window palettes tL = (10, 10) bR = (wd / 2 - 10, ht - 10) tL2 = (wd / 2 + 10, 10) bR2 = (wd - 10, ht - 10) def angleError(raw_cx, FrameWidth): cc = float(raw_cx) va = float(75) #degrees
isAlarmOn = cv2.getTrackbarPos("Toggle Sound", title) isSMSOn = cv2.getTrackbarPos("Toggle SMS", title) if (isAlarmOn == 1): args["sound"] = True else: alarmCount = 0 args["sound"] = False if (isSMSOn == 1): isTwilioStarted = False if (twilioCount > 120 and isMessageSent == True and isTwilioStarted == False): cv2.setTrackbarPos("Toggle SMS", title, 0) else: isTwilioStarted = True isMessageSent = False twilioCount = 0 #If 'q' pressed, break from loop key = cv2.waitKey(1) & 0xFF if key == ord("q"): break #Update FPS Counter fps.update() #Stop timer and display FPS fps.stop()
old = obj_map.keys()[choice] print 'update', old, 'to:', new = raw_input() if edit_obj == old: edit_obj = new old_val = obj_map[old] obj_map.pop(old) obj_map[new] = old_val for i in range(len(annot)): if old in annot[i]: old_val = annot[i][old] annot[i].pop(old) annot[i][new] = old_val if k==27: break if k==ord(' '): if frame_no < len(frames)-1: frame_no +=1 cv2.setTrackbarPos('frame#', 'frame', frame_no) print 'save modified annotations? Press (y/n)' choice = cv2.waitKey(0) if choice ==ord('y'): with open(out_annot, 'w') as outfile: json.dump(annot, outfile) print 'annotations dumped into', outfile
def tool(NAME_OF_SOURCE_VIDEO,PATH_FILE_NAME_TO_SAVE_RESULT,PATH_FILE\ ,start_frame=[],end_frame=[],last_store=[None]): videoReader = cv2.VideoCapture(PATH_FILE + "/" + NAME_OF_SOURCE_VIDEO) length = int(videoReader.get(cv2.CAP_PROP_FRAME_COUNT)) cv2.namedWindow('Frame') cv2.createTrackbar('scrub bar', 'Frame', 0, length, nothing) #cv2.createTrackbar('progress bar', 'Frame', 0, length,nothing) #cv2.createTrackbar('end', 'mywindow', 100, length, onChange) #onChange(0,videoReader) #end = cv2.getTrackbarPos('end', 'Frame') shouldSaveResult = (PATH_FILE_NAME_TO_SAVE_RESULT != None) listOfForwardTime = [] # frame_cout = 0 #start_frame=[] #end_frame=[] start_done = False end_done = False curent_BORDER_COLOR = none_act_BORDER_COLOR if len(start_frame) >= 0: if len(start_frame) == len(end_frame): text_used = "nothing recording [" + str(start_frame) + "," + str( end_frame) + "]" curent_BORDER_COLOR = none_act_BORDER_COLOR else: text_used = "Action recording [" + str(start_frame) + "," + str( end_frame) + "]" curent_BORDER_COLOR = recorde_BORDER_COLOR start_done = True else: text_used = "nothing recording [[],[]]" # currentImage_store=[] # while isCurrentFrameValid: # targetSize = DISPLAY_IMAGE_SIZE - 2 * BORDER_SIZE # currentImage_store.append(cv2.resize(currentImage, (targetSize, targetSize))) loop_end = True pues = False #last_store=[None] while loop_end: videoReader.set(1, frame_cout) isCurrentFrameValid, currentImage = videoReader.read() cv2.imshow('Frame', currentImage) targetSize = DISPLAY_IMAGE_SIZE - 2 * BORDER_SIZE currentImage = cv2.resize(currentImage, (targetSize, targetSize)) #borrder coler resultImage = cv2.copyMakeBorder(currentImage, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, cv2.BORDER_CONSTANT, value=curent_BORDER_COLOR) #text wrapped_text = textwrap.wrap(text_used, width=40) iy = 0 for line in wrapped_text: textsize = cv2.getTextSize(line, font, fontScale, lineType)[0] gap = textsize[1] + 10 y = int((topLeftCornerOfText[0] + textsize[1])) + iy * gap x = topLeftCornerOfText[1] #- textsize[0]) / 2) resultImage = cv2.putText(resultImage, line, (x, y), font, fontScale, fontColor, lineType) iy = iy + 1 #frame cout resultImage = cv2.putText(resultImage, str(frame_cout) + "/" + str(length), bottomLeftCornerOfText, font, fontScale, fontColor, lineType) #file name resultImage = cv2.putText(resultImage, " - " + str(NAME_OF_SOURCE_VIDEO), bottomRightCornerOfText, font, fontScale, fontColor, lineType) cv2.imshow('Frame', resultImage) userResponse = cv2.waitKey(40) if userResponse == ord('s'): #and end_done==False: if start_done == False: start_frame.append(frame_cout) last_store.append("start_store") print("start frame " + str(start_frame)) #print("start_done "+str(start_done)) start_done = True #print("start_done " + str(start_done)) curent_BORDER_COLOR = recorde_BORDER_COLOR text_used = "Action recording [" + str( start_frame) + "," + str(end_frame) + "]" else: end_frame.append(frame_cout) last_store.append("end_store") print("end frame " + str(end_frame)) curent_BORDER_COLOR = none_act_BORDER_COLOR text_used = "nothing recording [" + str( start_frame) + "," + str(end_frame) + "]" #end_done=True start_done = False if userResponse == ord('d'): #and end_done==False: if last_store[-1] == "start_store": del start_frame[-1] del last_store[-1] curent_BORDER_COLOR = none_act_BORDER_COLOR text_used = "nothing recording [" + str( start_frame) + "," + str(end_frame) + "]" start_done = False elif last_store[-1] == "end_store": del end_frame[-1] del last_store[-1] curent_BORDER_COLOR = recorde_BORDER_COLOR text_used = "Action recording [" + str( start_frame) + "," + str(end_frame) + "]" start_done = True elif last_store[-1] == None: print("silly you nothing to get rid of yet") #userResponse = cv2.waitKey(25) if userResponse == ord('q'): #if userResponse == ord('q'): loop_end = False videoReader.release() #cv2.destroyAllWindows() break #else: #isCurrentFrameValid, currentImage = videoReader.read() barFrame = cv2.getTrackbarPos('scrub bar', 'Frame') if userResponse == ord('z'): #27: #frame_cout = frame_cout - 1 barFrame = barFrame - 1 userResponse = cv2.waitKey(40) elif userResponse == ord('c'): #frame_cout = frame_cout + 4 barFrame = barFrame + 4 userResponse = cv2.waitKey(40) elif userResponse == ord('v'): #frame_cout = frame_cout + 6 barFrame = barFrame + 6 userResponse = cv2.waitKey(40) elif userResponse == ord('x'): if pues != True: #frame_cout = frame_cout #+ 2 pues = True else: #frame_cout = frame_cout pues = False elif pues == True: barFrame = barFrame #frame_cout = frame_cout else: barFrame = barFrame + 1 #frame_cout = frame_cout + 1 # get current positions of four trackbars #cv2.setTrackbarPos('scrub bar', 'Frame', frame_cout) #barFrame = cv2.getTrackbarPos('scrub bar', 'Frame') #print(barFrame) #print("frame "+str(frame_cout)) if int(barFrame) != int(frame_cout + 1): #cv2.setTrackbarPos('scrub bar', 'Frame', barFrame) #fame_cout=fame_cout+1 #print("changeing the due to") frame_cout = barFrame cv2.setTrackbarPos('scrub bar', 'Frame', frame_cout) # barFrame == else: frame_cout = frame_cout + 1 cv2.setTrackbarPos('scrub bar', 'Frame', frame_cout) # barFrame == #print("frame_cout "+str(frame_cout)) #print("frame " + str(frame_cout)) #print(length) if frame_cout == length - 1 or frame_cout == length or frame_cout > length: loop_end = False #if frame_cout # end mesage resultImage = cv2.putText(resultImage, str("Ended? ('N' to next 'R' to redo)"), centerOfText, font, fontScale, fontColor, lineType) cv2.imshow('Frame', resultImage) # When everything done, release the video capture object videoReader.release() #cv2.destroyAllWindows() print("start frame " + str(start_frame)) #if end_frame==None: print("end frame " + str(end_frame)) return start_frame, end_frame, last_store
def adjustValues(img, colorLower, colorHigher): """ Simple GUI to pick HSV values for a given mask. Has sliders where you can adjust, in convenient alphabetical order, H, S, and V for lower and upper bounds. Continually loops through, updating and displaying the image mask. Indispensable for picking out colors. Arguments: img {np.ndarray} -- rgb image of interest colorLower {3-Tuple} -- initial hsv lower bound colorHigher {3-Tuple} -- initial hsb higher bound """ # Make and resize window cv2.namedWindow('TB', cv2.WINDOW_NORMAL) cv2.resizeWindow('TB', (350, 350)) # Set up trackbars # Note: they will be alphabetized cv2.namedWindow('TB', cv2.WINDOW_NORMAL) cv2.createTrackbar('HLower', 'TB', 0, 255, nothing) cv2.createTrackbar('SLower', 'TB', 0, 255, nothing) cv2.createTrackbar('VLower', 'TB', 0, 255, nothing) cv2.createTrackbar('HHigher', 'TB', 0, 255, nothing) cv2.createTrackbar('SHigher', 'TB', 0, 255, nothing) cv2.createTrackbar('VHigher', 'TB', 0, 255, nothing) #initialize trackbar positions to function arguments hL = cv2.setTrackbarPos('HLower', 'TB', colorLower[0]) sL = cv2.setTrackbarPos('SLower', 'TB', colorLower[1]) vL = cv2.setTrackbarPos('VLower', 'TB', colorLower[2]) hH = cv2.setTrackbarPos('HHigher', 'TB', colorHigher[0]) sH = cv2.setTrackbarPos('SHigher', 'TB', colorHigher[1]) vH = cv2.setTrackbarPos('VHigher', 'TB', colorHigher[2]) #Continually monitor trackbar position and re-run mask creation while (True): hL = cv2.getTrackbarPos('HLower', 'TB') sL = cv2.getTrackbarPos('SLower', 'TB') vL = cv2.getTrackbarPos('VLower', 'TB') hH = cv2.getTrackbarPos('HHigher', 'TB') sH = cv2.getTrackbarPos('SHigher', 'TB') vH = cv2.getTrackbarPos('VHigher', 'TB') img = cv2.GaussianBlur(img, (3, 3), 0) # do hsv thresholding blurred = cv2.GaussianBlur(img, (3, 3), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_RGB2HSV) colorLower = (hL, sL, vL) colorHigher = (hH, sH, vH) print("colorLower: ", colorLower) print("colorHigher: ", colorHigher) mask = getMask(hsv, colorLower, colorHigher) cv2.imshow('Mask', mask & img) key = cv2.waitKey(33) & 0xFF if key == ord('q'): quit() elif key == ord('p'): pdb.set_trace()
th_max = cv2.getTrackbarPos('max', window_settings) area_delta = cv2.getTrackbarPos('area_delta', window_settings) hsv = cv2.cvtColor(right, cv2.COLOR_BGR2HSV) B,G,R = cv2.split(right) H,S,V = cv2.split(hsv) input = B if (rx,ry) == (-1, -1): rx,ry,mouse = initialize(input, th, th_max) area = cv2.contourArea(mouse)/100 newTh = max(area - area_delta, 9) newTh_max = max(area + area_delta, 16) cv2.setTrackbarPos('th', window_settings, int(newTh)) cv2.setTrackbarPos('max', window_settings, int(newTh_max)) contours, otsu_threshold, open, filterSmall = findRat(input, th, th_max) rx,ry,new_mouse = filterMouse(contours, (rx, ry)) if type(new_mouse) is not bool: mouse = new_mouse area = cv2.contourArea(mouse)/100 newTh = max(area - area_delta, 9) newTh_max = max(area + area_delta, 16) cv2.setTrackbarPos('th', window_settings, int(newTh)) cv2.setTrackbarPos('max', window_settings, int(newTh_max)) output = input.copy()
def start(self): cv2.namedWindow('edges') cv2.namedWindow('Hough') cv2.namedWindow('HoughP') dummy = numpy.array([[0]]) cv2.imshow('edges', dummy) cv2.imshow('Hough', dummy) cv2.imshow('HoughP', dummy) self.h_lines = None self.p_lines = None cv2.createTrackbar('thresh1', 'edges', 0, 255, lambda self: None) cv2.createTrackbar('thresh2', 'edges', 0, 255, lambda self: None) cv2.setTrackbarPos('thresh1', 'edges', 50) cv2.setTrackbarPos('thresh2', 'edges', 150) cv2.createTrackbar('r_tol', 'Hough', 1, 10, lambda self: None) cv2.createTrackbar('deg_tol', 'Hough', 1, 18, lambda self: None) cv2.createTrackbar('h_thresh', 'Hough', 1, 250, lambda self: None) cv2.createTrackbar('h_main', 'Hough', 0, 1, lambda self: None) cv2.setTrackbarPos('r_tol', 'Hough', 2) cv2.setTrackbarPos('deg_tol', 'Hough', 2) cv2.setTrackbarPos('h_thresh', 'Hough', 120) cv2.setTrackbarPos('h_main', 'Hough', 0) cv2.createTrackbar('minLineLength', 'HoughP', 1, 80, lambda self: None) cv2.createTrackbar('maxLineGap', 'HoughP', 1, 50, lambda self: None) cv2.createTrackbar('p_thresh', 'HoughP', 1, 250, lambda self: None) cv2.setTrackbarPos('minLineLength', 'HoughP', 40) cv2.setTrackbarPos('maxLineGap', 'HoughP', 20) cv2.setTrackbarPos('p_thresh', 'HoughP', 20) cv2.createTrackbar('p_main', 'HoughP', 0, 1, lambda self: None) cv2.setTrackbarPos('p_main', 'HoughP', 0) super().start()