def _show_image(self): self.subLock.acquire(True) local_image = deepcopy(self._np_image) self.subLock.release() # draw circles for idx, points in enumerate(self._roi_points): cv2.circle(local_image, (points[0], points[1]), 5, (255, 0, 0), 2) # draw green lines cv2.polylines(local_image, np.int32([np.array(self._roi_points)]), 1, (0, 255, 0), 2) cv2.polylines(local_image, np.int32([np.array( self._other_roi_points)]), 1, (0, 255, 0), 2) cv.ShowImage("Learn Play game RGB", cv.fromarray(local_image)) cv.SetMouseCallback("Learn Play game RGB", self._on_mouse_click, 0) cv.CreateTrackbar("Gain", "Learn Play game RGB", self._gain_slider, 100, self._on_gain_slider) cv.CreateTrackbar("Red Threshold", "Learn Play game RGB", self._inrange_colour_thresh, 500, self._on_red_slider) cv.CreateTrackbar("High red", "Learn Play game RGB", self._high_colour_slider, 40, self._on_high_colour_slider) cv.CreateTrackbar("Low red", "Learn Play game RGB", self._low_colour_slider, 40, self._on_low_colour_slider) cv.WaitKey(3)
def __init__(self, node_name): ROS2OpenCV2.__init__(self, node_name) self.node_name = node_name # The minimum saturation of the tracked color in HSV space, # as well as the min and max value (the V in HSV) and a # threshold on the backprojection probability image. self.smin = rospy.get_param("~smin", 85) self.vmin = rospy.get_param("~vmin", 50) self.vmax = rospy.get_param("~vmax", 254) self.threshold = rospy.get_param("~threshold", 50) # Create a number of windows for displaying the histogram, # parameters controls, and backprojection image cv.NamedWindow("Histogram", cv.CV_WINDOW_NORMAL) cv.MoveWindow("Histogram", 700, 50) cv.NamedWindow("Parameters", 0) cv.MoveWindow("Parameters", 700, 325) cv.NamedWindow("Backproject", 0) cv.MoveWindow("Backproject", 700, 600) # Create the slider controls for saturation, value and threshold cv.CreateTrackbar("Saturation", "Parameters", self.smin, 255, self.set_smin) cv.CreateTrackbar("Min Value", "Parameters", self.vmin, 255, self.set_vmin) cv.CreateTrackbar("Max Value", "Parameters", self.vmax, 255, self.set_vmax) cv.CreateTrackbar("Threshold", "Parameters", self.threshold, 255, self.set_threshold) # Initialize a number of variables self.hist = None self.track_window = None self.show_backproj = False
def __init__(self, img0): self.thresh1 = 255 self.thresh2 = 30 self.level =4 self.storage = cv.CreateMemStorage() cv.NamedWindow("Source", 0) cv.ShowImage("Source", img0) cv.NamedWindow("Segmentation", 0) cv.CreateTrackbar("Thresh1", "Segmentation", self.thresh1, 255, self.set_thresh1) cv.CreateTrackbar("Thresh2", "Segmentation", self.thresh2, 255, self.set_thresh2) self.image0 = cv.CloneImage(img0) self.image1 = cv.CloneImage(img0) cv.ShowImage("Segmentation", self.image1)
def __init__(self, src_image): self.src_image = src_image self.dst_image = cv.CloneMat(src_image) self.hist_image = cv.CreateImage((320, 200), 8, 1) self.hist = cv.CreateHist([hist_size], cv.CV_HIST_ARRAY, ranges, 1) self.brightness = 0 self.contrast = 0 cv.NamedWindow("image", 0) cv.NamedWindow("histogram", 0) cv.CreateTrackbar("brightness", "image", 100, 200, self.update_brightness) cv.CreateTrackbar("contrast", "image", 100, 200, self.update_contrast) self.update_brightcont()
def __init__(self, threshold=20, showWindows=False): self.writer = None self.font = None self.show = showWindows #Either or not show the 2 windows self.frame = None root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.chdir(os.path.join(root_path, "etc", "video")) self.capture = cv.CaptureFromCAM(0) self.frame = cv.QueryFrame( self.capture) #Take a frame to init recorder self.gray_frame = cv.CreateImage(cv.GetSize(self.frame), cv.IPL_DEPTH_8U, 1) self.average_frame = cv.CreateImage(cv.GetSize(self.frame), cv.IPL_DEPTH_32F, 3) self.absdiff_frame = None self.previous_frame = None self.surface = self.frame.width * self.frame.height self.currentsurface = 0 self.currentcontours = None self.threshold = threshold self.isRecording = False self.trigger_time = 0 #Hold timestamp of the last detection if showWindows: cv.NamedWindow("Image") cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold, 100, self.onChange)
def __init__(self, threshold=25, doRecord=True, showWindows=True): self.writer = None self.font = None self.doRecord = doRecord #Either or not record the moving object self.show = showWindows #Either or not show the 2 windows self.frame = None self.capture = cv.CaptureFromCAM(0) self.frame = cv.QueryFrame( self.capture) #Take a frame to init recorder if doRecord: self.initRecorder() self.gray_frame = cv.CreateImage(cv.GetSize(self.frame), cv.IPL_DEPTH_8U, 1) self.average_frame = cv.CreateImage(cv.GetSize(self.frame), cv.IPL_DEPTH_32F, 3) self.absdiff_frame = None self.previous_frame = None self.surface = self.frame.width * self.frame.height self.currentsurface = 0 self.currentcontours = None self.threshold = threshold self.isRecording = False self.trigger_time = 0 #Hold timestamp of the last detection if showWindows: cv.NamedWindow("Image") cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold, 100, self.onChange)
def __init__(self, threshold=8, doRecord=True, showWindows=True): self.writer = None self.font = None self.doRecord = doRecord #Either or not record the moving object self.show = showWindows #Either or not show the 2 windows self.frame = None self.capture = cv.CaptureFromCAM(0) self.frame = cv.QueryFrame( self.capture) #Take a frame to init recorder if doRecord: self.initRecorder() self.frame1gray = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) #Gray frame at t-1 cv.CvtColor(self.frame, self.frame1gray, cv.CV_RGB2GRAY) #Will hold the thresholded result self.res = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) self.frame2gray = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) #Gray frame at t self.width = self.frame.width self.height = self.frame.height self.nb_pixels = self.width * self.height self.threshold = threshold self.isRecording = False self.trigger_time = 0 #Hold timestamp of the last detection if showWindows: cv.NamedWindow("Image") cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold, 100, self.onChange)
def __init__(self, node_name): ROS2OpenCV2.__init__(self, node_name) self.node_name = node_name self.color_under_detect = rospy.get_param("~color_under_detect", "red") # call masking alglorthm to get the color mask self.mymask = Masking(color=self.color_under_detect, shape="triangle", masker=None, detector=None, matcher=None, matching_method=None) # The minimum saturation of the tracked color in HSV space, # as well as the min and max value (the V in HSV) and a # threshold on the backprojection probability image. self.smin = rospy.get_param("~smin", 85) self.vmin = rospy.get_param("~vmin", 50) self.vmax = rospy.get_param("~vmax", 254) self.threshold = rospy.get_param("~threshold", 50) # Create a number of windows for displaying the histogram, # parameters controls, and backprojection image cv.NamedWindow("Histogram", cv.CV_WINDOW_NORMAL) cv.MoveWindow("Histogram", 700, 50) cv.NamedWindow("Parameters", 0) cv.MoveWindow("Parameters", 700, 325) cv.NamedWindow("Backproject", 0) cv.MoveWindow("Backproject", 700, 600) cv.NamedWindow("Tracked_obj", 0) cv.MoveWindow("Tracked_obj", 1000, 50) # Create the slider controls for saturation, value and threshold cv.CreateTrackbar("Saturation", "Parameters", self.smin, 255, self.set_smin) cv.CreateTrackbar("Min Value", "Parameters", self.vmin, 255, self.set_vmin) cv.CreateTrackbar("Max Value", "Parameters", self.vmax, 255, self.set_vmax) cv.CreateTrackbar("Threshold", "Parameters", self.threshold, 255, self.set_threshold) # Initialize a number of variables self.hist = None self.track_window = None self.show_backproj = False
def _show_image(self): self.subLock.acquire(True) local_image = deepcopy(self._np_image) self.subLock.release() for idx, points in enumerate(self._roi_points): cv2.circle(local_image, (points[0], points[1]), 5, (255, 0, 0), 2) cv2.polylines(local_image, np.int32([np.array(self._roi_points)]), 1, (0, 255, 0), 2) cv2.imshow("Connect Four RGB", local_image) cv.SetMouseCallback("Connect Four RGB", self._on_mouse_click, 0) cv.CreateTrackbar("Gain", "Connect Four RGB", self._gain_slider, 100, self._on_gain_slider) cv.CreateTrackbar("Red Threshold", "Connect Four RGB", self._red_thresh, 500, self._on_red_slider) cv.CreateTrackbar("Yellow Threshold", "Connect Four RGB", self._yellow_thresh, 500, self._on_yellow_slider) cv.WaitKey(3)
def __init__(self): self.capture = cv.CaptureFromCAM(0) cv.NamedWindow("CamShiftDemo", 1) cv.NamedWindow("Histogram", 1) cv.SetMouseCallback("CamShiftDemo", self.on_mouse) self.drag_start = None # Set to (x,y) when mouse starts drag self.track_window = None # Set to rect when the mouse drag finishes cv.CreateTrackbar("Vmin", "CamShiftDemo", self.vmin, 256, self.onVminUpdate) cv.CreateTrackbar("Vmax", "CamShiftDemo", self.vmax, 256, self.onVmaxUpdate) cv.CreateTrackbar("Smin", "CamShiftDemo", self.smin, 256, self.onSminUpdate) print( "Keys:\n" " ESC - quit the program\n" " b - switch to/from backprojection view\n" "To initialize tracking, drag across the object with the mouse\n")
def __init__(self, name, start_values): self.name = name cv.NamedWindow(name, flags=cv.CV_WINDOW_NORMAL) cv.MoveWindow(name, 20, 20) assert len(start_values) == 6 self.values = OrderedDict() for channel, value in start_values.items(): self.values[channel] = value cv.CreateTrackbar(channel, name, value, 255, self.make_modifier(channel))
def __init__(self, source_image, slider_pos, use_intensity): self.source_color = source_image self.source_image = cv.CreateImage( (self.source_color.width, self.source_color.height), 8, 1) cv.CvtColor(self.source_color, self.source_image, cv.CV_BGR2GRAY) self.intensity = use_intensity if self.intensity == False: # create the output im self.col_edge = cv.CreateImage( (self.source_image.width, self.source_image.height), 8, 3) self.edge = cv.CreateImage( (self.source_image.width, self.source_image.height), 8, 1) cv.CreateTrackbar("Threshold", "Result", slider_pos, 255, self.process_image) self.process_image(slider_pos)
def __init__(self, threshold=20, doRecord=True, showWindows=True): self.writer = None self.font = None self.doRecord = doRecord #Either or not record the moving object self.show = showWindows #Either or not show the 2 windows self.frame = None # Initiate mongodb connections # self.MotionCollection = mongoLABhelper.startMotionDatabaseURI("MotionCollection", "uri:port") # self.AlertCollection = mongoLABhelper.startAlertDatabaseURI("AlertCollection", "uri:port") self.capture = cv.CaptureFromCAM(0) self.frame = cv.QueryFrame( self.capture) #Take a frame to init recorder self.frame1gray = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) #Gray frame at t-1 cv.CvtColor(self.frame, self.frame1gray, cv.CV_RGB2GRAY) #Will hold the thresholded result self.res = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) self.frame2gray = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U) #Gray frame at t self.width = self.frame.width self.height = self.frame.height self.nb_pixels = self.width * self.height self.threshold = threshold self.isRecording = False self.trigger_time = 0 #Hold timestamp of the last detection if showWindows: cv.NamedWindow("Image") cv.CreateTrackbar("Detection threshold: ", "Image", self.threshold, 100, self.onChange)
def __init__(self, source_image, slider_pos): self.source_image = source_image cv.CreateTrackbar("Threshold", "Result", slider_pos, 255, self.process_image) self.process_image(slider_pos)
print "\tm - switch mask mode" print "\tr - restore the original image" print "\ts - use null-range floodfill" print "\tf - use gradient floodfill with fixed(absolute) range" print "\tg - use gradient floodfill with floating(relative) range" print "\t4 - use 4-connectivity mode" print "\t8 - use 8-connectivity mode" color_img = cv.CloneImage(im) gray_img0 = cv.CreateImage((color_img.width, color_img.height), 8, 1) cv.CvtColor(color_img, gray_img0, cv.CV_BGR2GRAY) gray_img = cv.CloneImage(gray_img0) mask = cv.CreateImage((color_img.width + 2, color_img.height + 2), 8, 1) cv.NamedWindow("image", 1) cv.CreateTrackbar("lo_diff", "image", lo_diff, 255, update_lo) cv.CreateTrackbar("up_diff", "image", up_diff, 255, update_up) cv.SetMouseCallback("image", on_mouse) while True: if (is_color): cv.ShowImage("image", color_img) else: cv.ShowImage("image", gray_img) c = cv.WaitKey(0) % 0x100 if c == 27: print("Exiting ...") sys.exit(0) elif c == ord('c'):
# create the image for putting in it the founded contours contours_image = cv.CreateImage((im.width, im.height), 8, 3) print type(col_edge) print im.width # convert to grayscale for canny gray = cv.CreateImage((im.width, im.height), 8, 1) edge = cv.CreateImage((im.width, im.height), 8, 1) cv.CvtColor(im, gray, cv.CV_BGR2GRAY) # create the window for canny edge cv.NamedWindow(win_name, cv.CV_WINDOW_NORMAL) # create the trackbar for canny cv.CreateTrackbar(trackbar_name, win_name, 1, 40, on_trackbar) # show the canny image on_trackbar(0) # wait a key pressed to end and open contour code cv.WaitKey(0) cv.SaveImage('C:\\3d-Model\\bin\\segmentation_files\\pic_seg.jpg', col_edge) # save the image as jpg #save the image as svg #files="C:\\3d-Model\\bin\\segmentation_files\\pic_seg.jpg" #pngFile = open(files, 'rb') #base64data = pngFile.read().encode("base64").replace('\n','') #base64String = '<image xlink:href="data:image/png;base64,{0}" width="im.width" height="im.height" x="0" y="0" />'.format(base64data) #f = open(os.path.splitext(files)[0]+".svg",'w')
def main(argv=None): global opts opts, args = parse_args(argv) init_logger(opts) logging.debug(opts) logging.debug(args) global cw cw = csv.writer(sys.stdout, lineterminator='\n') capture = cv2.VideoCapture(opts.movie) global video_width video_width = capture.get(3) global video_height video_height = capture.get(4) def onChange2(val): global blurVal blurVal = val + 1 if val % 2 == 0 else val print "Changed Blur to " + str(blurVal) def onChange3(val): global threshVal threshVal = val print "Changed Treshold to " + str(threshVal) global blurVal blurVal = int(opts.blur) if opts.blur else 7 global threshVal threshVal = int(opts.threshold) if opts.threshold else 7 if opts.visualize: cv.NamedWindow("Image") cv.CreateTrackbar("Blur", "Image", 1, 25, onChange2) cv.CreateTrackbar("Threshold", "Image", 1, 255, onChange3) cv.SetTrackbarPos("Blur", "Image", blurVal) cv.SetTrackbarPos("Threshold", "Image", threshVal) global boxwindow boxwindow = int(opts.boxwindow) if opts.boxwindow else 10 playbackspeed = int(opts.playbackspeed) if opts.playbackspeed else 100 accumulator_weight = float(opts.accumulator) if opts.accumulator else 0.001 frame_cnt = 0 object_db = ObjectDatabase() status = True _, f = capture.read() frame = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) bg_avg = np.float32(frame) # reset capture capture.release() capture = cv2.VideoCapture(opts.movie) fourcc = cv2.cv.CV_FOURCC('M', 'J', 'P', 'G') output_writer = cv2.VideoWriter() if opts.output: output_writer.open( opts.output, fourcc, 21.37, (int(video_width), int(video_height)), True) while status: status, img = capture.read() frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if opts.subtractbg: cv2.accumulateWeighted(frame, bg_avg, accumulator_weight) res1 = frame if opts.subtractbg: res1 = cv2.absdiff(frame, cv2.convertScaleAbs(bg_avg)) blurred = cv2.GaussianBlur(res1, (blurVal, blurVal), 0) ret, thresh = cv2.threshold(blurred, threshVal, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours( thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) logging.debug("\n\nCalling Add_Contours") object_db.add_contours(frame_cnt, contours) for mc in reversed(object_db.prev_OverlapMovingObjects): if len(mc.frames.keys()) > 0: for f in mc.frames.keys(): cp = mc.frames[f] cv2.circle( img, (int(cp.cx), int(cp.cy)), int(cp.radius), mc.color, 1) if len(mc.frames.keys()) == 1: cv2.drawContours( img, [mc.get_last_contour()], -1, (0, 255, 0), -1, 1) if opts.visualize: cv2.imshow("Image", img) c = cv2.waitKey(playbackspeed) if c == 27: # Break if user enters 'A'. frame_cnt += 1 next if c == 97: break if opts.output: output_writer.write(img) frame_cnt += 1 if opts.output: output_writer.release() cv2.destroyAllWindows() capture.release()
contours = cv.FindContours(img_result, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE) print contours # draw contours in red and green cv.DrawContours (img_result, #dest image contours, #input contours _red, #color of external contour _green, #color of internal contour levels, #maxlevel of contours to draw _contour_thickness, cv.CV_AA, #line type (0, 0)) #offset pass def on_trackbar_smooth(position): cv.Smooth(img_gray, img_gray, smoothtype=cv.CV_BLUR, param1=2*position+1) pass src_file = 'runtime/hand_color.jpg' src_img = cv.LoadImage(src_file) src_img_size = cv.GetSize(src_img) img_gray = cv.CreateImage(src_img_size, 8, 1) cv.CvtColor(src_img, img_gray, cv.CV_BGR2GRAY) cv.NamedWindow("converted-image", 1) cv.ShowImage("converted-image", img_gray) cv.Smooth(img_gray, img_gray, smoothtype=cv.CV_BLUR) cv.NamedWindow("contours", 1) print cv.CreateTrackbar("(pre) smoothness", 'contours', 0, 7, on_trackbar_smooth) print cv.CreateTrackbar ("canny threshold", "contours", 0, 7, on_trackbar) cv.ShowImage("contours", img_gray) cv.WaitKey(0)
import cv2.cv as cv im = cv.LoadImage("t.png", cv.CV_LOAD_IMAGE_GRAYSCALE) thresholded = cv.CreateImage(cv.GetSize(im), 8, 1) def onChange(val): cv.Threshold(im, thresholded, val, 255, cv.CV_THRESH_BINARY) cv.ShowImage("Image", thresholded) onChange(100) cv.CreateTrackbar("Thresh", "Image", 100, 255, onChange) cv.WaitKey(0)
def __init__(self, node_name): self.node_name = node_name rospy.init_node(node_name) rospy.loginfo("Starting node " + str(node_name)) rospy.on_shutdown(self.cleanup) self.drink_type="" self._wake=0 # Initialize the Region of Interest and its publisher self.ROI = RegionOfInterest() self.roi_pub = rospy.Publisher("/roi", RegionOfInterest, queue_size=1) self.dis_pub = rospy.Publisher("dist", Int32, queue_size=1) self.drink_ = rospy.Subscriber('drink_type',String,self.callbackDrink) self.wake_ = rospy.Subscriber('ros2_wake',Int32,self.callbackWake) self.hmin = rospy.get_param("~hmin", 22) self.hmax = rospy.get_param("~hmax", 62) self.smin = rospy.get_param("~smin", 115) self.smax = rospy.get_param("~smax", 255) self.vmin = rospy.get_param("~vmin", 50) self.vmax = rospy.get_param("~vmax", 255) ###### while self._wake!=1: rospy.sleep(1) if self.drink_type == '雪碧': #blue self.hmin = rospy.get_param("~hmin", 122) self.hmax = rospy.get_param("~hmax", 157) self.smin = rospy.get_param("~smin", 59) self.smax = rospy.get_param("~smax", 255) self.vmin = rospy.get_param("~vmin", 59) self.vmax = rospy.get_param("~vmax", 255) rospy.loginfo("匹配雪碧") if self.drink_type == '橙汁': #yellow self.hmin = rospy.get_param("~hmin", 70) self.hmax = rospy.get_param("~hmax", 155) self.smin = rospy.get_param("~smin", 90) self.smax = rospy.get_param("~smax", 255) self.vmin = rospy.get_param("~vmin", 50) self.vmax = rospy.get_param("~vmax", 255) rospy.loginfo("匹配橙汁") if self.drink_type == '可乐': #red self.hmin = rospy.get_param("~hmin", 155) self.hmax = rospy.get_param("~hmax", 190) self.smin = rospy.get_param("~smin", 67) self.smax = rospy.get_param("~smax", 224) self.vmin = rospy.get_param("~vmin", 83) self.vmax = rospy.get_param("~vmax", 223) rospy.loginfo("匹配可乐") ###### #self.show_text=rospy.get_param("~show_text",True) # Initialize a number of global variables self.frame = None self.frame_size = None self.frame_width = None self.frame_height = None self.depth_image = None self.marker_image = None self.display_image = None self.keystroke = None self.keep_marker_history = False self.cX=0 self.cY=0 cv.NamedWindow("Parameters", 0) cv.MoveWindow("Parameters", 700, 325) # Create the slider controls for saturation, value and threshold cv.CreateTrackbar("Min H", "Parameters", self.hmin, 255, self.set_hmin) cv.CreateTrackbar("Max H", "Parameters", self.hmax, 255, self.set_hmax) cv.CreateTrackbar("Min S", "Parameters", self.smin, 255, self.set_smin) cv.CreateTrackbar("Max S", "Parameters", self.smax, 255, self.set_smax) cv.CreateTrackbar("Min Value", "Parameters", self.vmin, 255, self.set_vmin) cv.CreateTrackbar("Max Value", "Parameters", self.vmax, 255, self.set_vmax) # Create the main display window self.cv_window_name = self.node_name cv.NamedWindow(self.cv_window_name, cv.CV_WINDOW_NORMAL) cv.NamedWindow("reality", cv.CV_WINDOW_NORMAL) cv.NamedWindow("depth", cv.CV_WINDOW_NORMAL) # Create the cv_bridge object self.bridge = CvBridge() # Subscribe to the image and depth topics and set the appropriate callbacks # The image topic names can be remapped in the appropriate launch file self.image_sub = rospy.Subscriber("input_rgb_image", Image, self.image_callback, queue_size=1) self.depth_sub = rospy.Subscriber("input_depth_image", Image, self.depth_callback, queue_size=1)
if len(sys.argv) > 1: gray = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_GRAYSCALE) else: url = 'https://code.ros.org/svn/opencv/trunk/opencv/samples/c/stuff.jpg' filedata = urllib2.urlopen(url).read() imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) cv.SetData(imagefiledata, filedata, len(filedata)) gray = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_GRAYSCALE) # Create the output image dist = cv.CreateImage((gray.width, gray.height), cv.IPL_DEPTH_32F, 1) dist8u1 = cv.CloneImage(gray) dist8u2 = cv.CloneImage(gray) dist8u = cv.CreateImage((gray.width, gray.height), cv.IPL_DEPTH_8U, 3) dist32s = cv.CreateImage((gray.width, gray.height), cv.IPL_DEPTH_32S, 1) # Convert to grayscale edge = cv.CloneImage(gray) # Create a window cv.NamedWindow(wndname, 1) # create a toolbar cv.CreateTrackbar(tbarname, wndname, edge_thresh, 255, on_trackbar) # Show the image on_trackbar(edge_thresh) # Wait for a key stroke; the same function arranges events processing cv.WaitKey(0)
# 2 - File action = 2 imgproc = None if action == 1: imgproc = Imgproc(0) else: imgproc = Imgproc(-1) kinect = None #if len(sys.argv) < 1: kinect = Kinect() cv2.namedWindow('Original, HSV, Thresh, Rects') cv2.namedWindow('Tuning Window') cv.CreateTrackbar("Lower H", 'Tuning Window', imgproc.COLOR_MIN[0], 255, update_lowerH) cv.CreateTrackbar("Lower S", 'Tuning Window', imgproc.COLOR_MIN[1], 255, update_lowerS) cv.CreateTrackbar("Lower V", 'Tuning Window', imgproc.COLOR_MIN[2], 255, update_lowerV) cv.CreateTrackbar("Upper H", 'Tuning Window', imgproc.COLOR_MAX[0], 255, update_upperH) cv.CreateTrackbar("Upper S", 'Tuning Window', imgproc.COLOR_MAX[1], 255, update_upperS) cv.CreateTrackbar("Upper V", 'Tuning Window', imgproc.COLOR_MAX[2], 255, update_upperV) while 1: # Load the image from the camera (or a static file for testing) if len(sys.argv) > 1:
def sd_loop(self): """ The main seizure detector loop - call this function to start the seizure detector. """ self.timeSeries = [] # array of times that data points were collected. self.maxFreq = None if (self.X11): cv.NamedWindow('Seizure_Detector', cv.CV_WINDOW_AUTOSIZE) cv.CreateTrackbar('FeatureTrackbar', 'Seizure_Detector', 0, self.MAX_COUNT, self.onTrackbarChanged) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, 8) # Intialise the video input source # ('camera' - may be a file or network stream though). #camera = cv.CaptureFromFile("rtsp://192.168.1.18/live_mpeg4.sdp") #camera = cv.CaptureFromFile("../testcards/testcard.mpg") #camera = cv.CaptureFromFile("/home/graham/laura_sample.mpeg") camera = cv.CaptureFromCAM(0) # Set the VideoWriter that produces the output video file. frameSize = (640, 480) videoFormat = cv.FOURCC('p', 'i', 'm', '1') # videoFormat = cv.FOURCC('l','m','p','4') vw = cv.CreateVideoWriter(self.videoOut, videoFormat, self.outputfps, frameSize, 1) if (vw == None): print "ERROR - Failed to create VideoWriter...." # Get the first frame. last_analysis_time = datetime.datetime.now() last_feature_search_time = datetime.datetime.now() last_frame_time = datetime.datetime.now() frame = cv.QueryFrame(camera) print "frame=" print frame # Main loop - repeat forever while 1: # Carry out initialisation, memory allocation etc. if necessary if self.image is None: self.image = cv.CreateImage(cv.GetSize(frame), 8, 3) self.image.origin = frame.origin grey = cv.CreateImage(cv.GetSize(frame), 8, 1) prev_grey = cv.CreateImage(cv.GetSize(frame), 8, 1) pyramid = cv.CreateImage(cv.GetSize(frame), 8, 1) prev_pyramid = cv.CreateImage(cv.GetSize(frame), 8, 1) # self.features = [] # copy the captured frame to our self.image object. cv.Copy(frame, self.image) # create a grey version of the image cv.CvtColor(self.image, grey, cv.CV_BGR2GRAY) # Look for features to track. if self.need_to_init: #cv.ShowImage ('loop_grey',grey) self.initFeatures(grey) self.timeSeries = [] self.maxFreq = None last_analysis_time = datetime.datetime.now() self.need_to_init = False # Now track the features, if we have some. if self.features != []: # we have points to track, so track them and add them to # our time series of positions. self.features, status, track_error = cv.CalcOpticalFlowPyrLK( prev_grey, grey, prev_pyramid, pyramid, self.features, (self.win_size, self.win_size), 3, (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03), self.flags) self.timeSeries.append((last_frame_time, self.features)) print "Features..." for featNo in range(len(self.features)): if (status[featNo] == 0): self.features[featNo] = (-1, -1) print status[featNo], self.features[featNo] # and plot them. for featNo in range(len(self.features)): pointPos = self.features[featNo] cv.Circle(self.image, (int(pointPos[0]), int(pointPos[1])), 3, (0, 255, 0, 0), -1, 8, 0) if (self.alarmActive[featNo] == 2): cv.Circle(self.image, (int(pointPos[0]), int(pointPos[1])), 10, (0, 0, 255, 0), 5, 8, 0) if (self.alarmActive[featNo] == 1): cv.Circle(self.image, (int(pointPos[0]), int(pointPos[1])), 10, (0, 0, 255, 0), 2, 8, 0) # there will be no maxFreq data until we have # run doAnalysis for the first time. if (not self.maxFreq == None): msg = "%d-%3.1f" % (featNo, self.maxFreq[featNo]) cv.PutText( self.image, msg, (int(pointPos[0] + 5), int(pointPos[1] + 5)), font, (255, 255, 255)) # end of for loop over features else: #print "Oh no, no features to track, and you haven't told me to look for more." # no features, so better look for some more... self.need_to_init = True # Is it time to analyse the captured time series. if ((datetime.datetime.now() - last_analysis_time).total_seconds() > self.Analysis_Period): if (len(self.timeSeries) > 0): self.doAnalysis() self.doAlarmCheck() last_analysis_time = datetime.datetime.now() else: # print "Not doing analysis - no time series data..." a = True # Is it time to re-acquire the features to track. if ((datetime.datetime.now() - last_feature_search_time).total_seconds() > self.Feature_Search_Period): print "resetting..." last_feature_search_time = datetime.datetime.now() self.need_to_init = True # save current data for use next time around. prev_grey, grey = grey, prev_grey prev_pyramid, pyramid = pyramid, prev_pyramid # we can now display the image if (self.X11): cv.ShowImage('Seizure_Detector', self.image) cv.WriteFrame(vw, self.image) # handle events c = cv.WaitKey(10) if c == 27: # user has press the ESC key, so exit break # Control frame rate by pausing if we are going too fast. frameTime = (datetime.datetime.now() - last_frame_time)\ .total_seconds() actFps = 1.0 / frameTime if (frameTime < 1 / self.inputfps): cv.WaitKey(1 + int(1000. * (1. / self.inputfps - frameTime))) # Grab the next frame last_frame_time = datetime.datetime.now() frame = cv.QueryFrame(camera)
import cv2.cv as cv im = cv.LoadImage("../img/lena.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE) thresholded = cv.CreateImage(cv.GetSize(im), 8, 1) def onChange(val): cv.Threshold(im, thresholded, val, 255, cv.CV_THRESH_BINARY) cv.ShowImage("Image", thresholded) onChange( 100 ) #Call here otherwise at startup. Show nothing until we move the trackbar cv.CreateTrackbar("Thresh", "Image", 100, 255, onChange) #Threshold value arbitrarily set to 100 cv.WaitKey(0) ''' capture=cv.CaptureFromCAM(0) value = 100 def onChange(val): global value value = val #cv.Threshold(im, dst, value, 255, cv.CV_THRESH_BINARY) cv.NamedWindow("Image") cv.CreateTrackbar("Mytrack", "Image", 100, 255, onChange) tmp = cv.QueryFrame(capture)
def Dilation(pos): element = cv.CreateStructuringElementEx(pos * 2 + 1, pos * 2 + 1, pos, pos, element_shape) cv.Dilate(src, dest, element, 1) cv.ShowImage("Erosion & Dilation", dest) if __name__ == "__main__": if len(sys.argv) > 1: src = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR) else: url = 'https://raw.github.com/Itseez/opencv/master/samples/c/fruits.jpg' filedata = urllib2.urlopen(url).read() imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) cv.SetData(imagefiledata, filedata, len(filedata)) src = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR) image = cv.CloneImage(src) dest = cv.CloneImage(src) cv.NamedWindow("Opening & Closing", 1) cv.NamedWindow("Erosion & Dilation", 1) cv.ShowImage("Opening & Closing", src) cv.ShowImage("Erosion & Dilation", src) cv.CreateTrackbar("Open", "Opening & Closing", 0, 10, Opening) cv.CreateTrackbar("Close", "Opening & Closing", 0, 10, Closing) cv.CreateTrackbar("Dilate", "Erosion & Dilation", 0, 10, Dilation) cv.CreateTrackbar("Erode", "Erosion & Dilation", 0, 10, Erosion) cv.WaitKey(0) cv.DestroyWindow("Opening & Closing") cv.DestroyWindow("Erosion & Dilation")
if __name__ == '__main__': if len(sys.argv) > 1: im = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR) else: url = 'https://raw.github.com/Itseez/opencv/master/samples/c/fruits.jpg' filedata = urllib2.urlopen(url).read() imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) cv.SetData(imagefiledata, filedata, len(filedata)) im = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR) # create the output im col_edge = cv.CreateImage((im.width, im.height), 8, 3) # convert to grayscale gray = cv.CreateImage((im.width, im.height), 8, 1) edge = cv.CreateImage((im.width, im.height), 8, 1) cv.CvtColor(im, gray, cv.CV_BGR2GRAY) # create the window cv.NamedWindow(win_name, cv.CV_WINDOW_AUTOSIZE) # create the trackbar cv.CreateTrackbar(trackbar_name, win_name, 1, 100, on_trackbar) # show the im on_trackbar(0) # wait a key pressed to end cv.WaitKey(0) cv.DestroyAllWindows()
def display_window(self): for heuristic, _ in self.heuristics: name = heuristic.__class__.__name__ cv.CreateTrackbar(name, "heuristics", 0, 1, self.make_set_debug(heuristic)) cv.CreateTrackbar("weights_" + name, "heuristics", 0, 1, self.make_set_weights(heuristic))
8, 0) cv.Ellipse(image, (dx + 273, dy + 100), (20, 35), 0, 0, 360, _white, -1, 8, 0) # create window and display the original picture in it cv.NamedWindow("image", 1) cv.ShowImage("image", image) # create the storage area storage = cv.CreateMemStorage(0) # find the contours contours = cv.FindContours(image, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE, (0, 0)) # comment this out if you do not want approximation contours = cv.ApproxPoly(contours, storage, cv.CV_POLY_APPROX_DP, 3, 1) # create the window for the contours cv.NamedWindow("contours", 1) # create the trackbar, to enable the change of the displayed level cv.CreateTrackbar("levels+3", "contours", 3, 7, on_trackbar) # call one time the callback, so we will have the 1st display done on_trackbar(_DEFAULT_LEVEL) # wait a key pressed to end cv.WaitKey(0) cv.DestroyAllWindows()
def main(args): if args.test: cv2.namedWindow('Control', cv2.WINDOW_AUTOSIZE) cv.CreateTrackbar("LowH", "Control", 0, 255, nothing) cv.CreateTrackbar("HighH", "Control", 0, 255, nothing) cv.CreateTrackbar("LowS", "Control", 0, 255, nothing) cv.CreateTrackbar("HighS", "Control", 0, 255, nothing) cv.CreateTrackbar("LowV", "Control", 0, 255, nothing) cv.CreateTrackbar("HighV", "Control", 0, 255, nothing) cv2.setTrackbarPos("LowH", "Control", filters.low_h) cv2.setTrackbarPos("HighH", "Control", filters.high_h) cv2.setTrackbarPos("LowS", "Control", filters.low_s) cv2.setTrackbarPos("HighS", "Control", filters.high_s) cv2.setTrackbarPos("LowV", "Control", filters.low_v) cv2.setTrackbarPos("HighV", "Control", filters.high_v) if args.filename: img = cv2.imread(args.filename, cv2.CV_LOAD_IMAGE_COLOR) elif args.camera: cap = cv2.VideoCapture( int(args.camera) if len(args.camera) < 3 else args.camera) else: raise RuntimeError("Please supply an image or a camera.") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: if args.test: filters.low_h = cv2.getTrackbarPos("LowH", "Control") filters.high_h = cv2.getTrackbarPos("HighH", "Control") filters.low_s = cv2.getTrackbarPos("LowS", "Control") filters.high_s = cv2.getTrackbarPos("HighS", "Control") filters.low_v = cv2.getTrackbarPos("LowV", "Control") filters.high_v = cv2.getTrackbarPos("HighV", "Control") if args.filename: img_copy = img.copy() elif args.camera: ret, img_copy = cap.read() filtered = hsv_filter(img_copy, filters.low_h, filters.high_h, filters.low_s, filters.high_s, filters.low_v, filters.high_v) filtered = open_close(filtered) contours, hierarchy = cv2.findContours(filtered.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) targets = list() for shape in contours: area = cv2.contourArea(shape) if area < AREA_THRESHOLD * img_copy.shape[0] * img_copy.shape[1]: continue x, y, w, h = calc_bbox(shape) targets.append(Target(area, x, x + w, (x + w / 2, y + h / 2))) if not args.novideo: distance = calc_distance(TAPE_WIDTH, w, img_copy.shape[1]) angle = calc_angle_x(x, img_copy.shape[1]) cv2.rectangle(img_copy, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(img_copy, 'Distance: {:.3}"'.format(distance), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) cv2.putText(img_copy, 'Angle: {:.3} deg'.format(angle), (int(x), int(y) + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) mid_x = 1.0 mid_y = 0 if len(targets) > 1: targets.sort(key=lambda tup: tup.area, reverse=True) if abs(targets[0].center[1] - targets[1].center[1]) <= Y_DIFF: if targets[0].left < targets[1].left: if targets[0].left < EDGE_THRESHOLD and targets[ 1].right > SCREENWIDTH - EDGE_THRESHOLD: mid_x = MIDSCREEN else: mid_x = (targets[1].left - targets[0].right) / 2 + targets[0].right else: if targets[1].left < EDGE_THRESHOLD and targets[ 0].right > SCREENWIDTH - EDGE_THRESHOLD: mid_x = MIDSCREEN else: mid_x = (targets[0].left - targets[1].right) / 2 + targets[1].right mid_y = sum(i.center[1] for i in targets[:2]) / 2 else: # if y test fails just send center of biggest box mid_x, mid_y = targets[0].center # print "Y mismatch" mid_x = mid_x - MIDSCREEN elif len(targets) == 1: # only one target found. send center of it mid_x, mid_y = targets[0].center mid_x = mid_x - MIDSCREEN #print mid_x try: s.sendto(str(mid_x), (IP, PORT)) except: try: s.sendto(str(mid_x), (IP, PORT)) except: pass if not args.novideo: cv2.circle(img_copy, (int(mid_x + MIDSCREEN), int(mid_y)), 10, (0, 0, 255), -1) cv2.drawContours(img_copy, contours, -1, (0, 0, 255)) cv2.imshow("Original", img_copy) cv2.imshow("Filtered", filtered) key = cv2.waitKey(30) if args.test and (key == 83 or key == 115): save = True break if key == 27: save = False break if args.camera: cap.release() if args.test and save: with open("filters.py", 'w') as f: f.write("low_h = {}\n".format(filters.low_h)) f.write("high_h = {}\n".format(filters.high_h)) f.write("low_s = {}\n".format(filters.low_s)) f.write("high_s = {}\n".format(filters.high_s)) f.write("low_v = {}\n".format(filters.low_v)) f.write("high_v = {}\n".format(filters.high_v)) cv2.destroyAllWindows()
s1 = 88 v1 = 92 h2 = 10 s2 = 222 v2 = 197 minDist = 20 pourcent = 80 thresh = None #image apres le traitement def rien(x): pass #creation des trackbar cv.CreateTrackbar("H_MIN", "cnt", h1, 255, rien) cv.CreateTrackbar("H_MAX", "cnt", h2, 255, rien) cv.CreateTrackbar("S_MIN", "cnt", s1, 255, rien) cv.CreateTrackbar("S_MAX", "cnt", s2, 255, rien) cv.CreateTrackbar("V_MIN", "cnt", v1, 255, rien) cv.CreateTrackbar("V_MAX", "cnt", v2, 255, rien) cv.CreateTrackbar("minDistCircle", "cnt", minDist, 20, rien) cv.CreateTrackbar("pourcentage_detection", "cnt", pourcent, 100, rien) def getPercentage(radius, contour): aire_objet = cv2.contourArea(contour) aire_cercle = math.pi * radius * radius return (aire_objet / aire_cercle) * 100