def __init__(self, ns): self.lock = threading.Lock() self.image_time = rospy.Time(0) self.info_time = rospy.Time(0) self.image = None self.interval = 0 self.features = None self.bridge = CvBridge() self.ns = ns self.max_interval = rospy.get_param('filter_intervals/min_duration') self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.30, 1.5, thickness=2) self.font1 = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.10, 1, thickness=1) self.info_sub = rospy.Subscriber(ns + '/camera_info', CameraInfo, self.info_cb) self.image_sub = rospy.Subscriber(ns + '/image_throttle', Image, self.image_cb) self.interval_sub = rospy.Subscriber(ns + '/settled_interval', Interval, self.interval_cb) self.features_sub = rospy.Subscriber(ns + '/features', CalibrationPattern, self.features_cb)
def log(self, text=None, frame=None): if self.measureDisplay: if text is None or text == "reset" or text == "init": if frame is not None and self.saveSamples: file = "/tmp/photo" + "-" + datetime.datetime.now( ).strftime("%Y%m%d%H%M%S%f") + "-" + "init" + ".png" cv.SaveImage(file, frame) self.measure_init = datetime.datetime.now() self.measure_next = self.measure_init print "\nStart getting Samples.." else: if text != "end": measure_now = datetime.datetime.now() diff = measure_now - self.measure_next print "\tSample: %s - %s micros" % (text, str(diff.microseconds)) if frame is not None and self.saveSamples: file = "/tmp/photo" + "-" + datetime.datetime.now( ).strftime("%Y%m%d%H%M%S%f") + "-" + text + ".png" cv.SaveImage(file, frame) self.measure_next = datetime.datetime.now() else: measure_now = datetime.datetime.now() diff = measure_now - self.measure_init print "Last Sample: %s micros" % (str(diff.microseconds)) if frame is not None and self.saveSamples: cv.PutText( frame, "Sample: " + time.strftime( "%d-%m-%Y %H:%M:%S", time.localtime()) + "-end", (10, cv.GetSize(frame)[1] - 10), cv.InitFont(cv.CV_FONT_HERSHEY_COMPLEX, .3, .3, 0.0, 1, cv.CV_AA), (255, 255, 255)) cv.SaveImage(file, frame)
def display_tracking(img_size, img1, img2, img_flow, homography): for x in range(0, img_size[0], 100): for y in range(0, img_size[1], 100): cv.Circle(img1, (x, y), 3, (0, 255, 0, 0), -1, 8, 0) point = cv.CreateMat(3, 1, cv.CV_64F) point[0, 0] = x point[1, 0] = y point[2, 0] = 1 newpoint = cv.CreateMat(3, 1, cv.CV_64F) cv.MatMul(homography, point, newpoint) cv.Circle(img2, (int(newpoint[0, 0]), int(newpoint[1, 0])), 3, (0, 255, 0, 0), -1, 8, 0) cv.Line(img_flow, (x, y), (int(newpoint[0, 0]), int(newpoint[1, 0])), cv.CV_RGB(255, 0, 0), 2) cv.Rectangle(img_flow, (0, 0), (150, 25), cv.CV_RGB(0, 0, 0), thickness=-1) cv.PutText( img_flow, "Good?: " + str(isHomographyGood(homography)), (0, 20), cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.75, 0.75, thickness=2), cv.CV_RGB(255, 255, 255)) cv.NamedWindow("Image1", 0) cv.NamedWindow("Image2", 0) cv.NamedWindow("Flow", 0) cv.ResizeWindow("Image1", int(0.5 * img_size[0]), int(0.5 * img_size[1])) cv.ResizeWindow("Image2", int(0.5 * img_size[0]), int(0.5 * img_size[1])) cv.ResizeWindow("Flow", int(0.5 * img_size[0]), int(0.5 * img_size[1])) cv.ShowImage("Image1", img1) cv.ShowImage("Image2", img2) cv.ShowImage("Flow", img_flow) cv.WaitKey(0)
def main(): while True: cv.NamedWindow('a_window', cv.CV_WINDOW_AUTOSIZE) #logfiles = sorted([ f for f in os.listdir(report_dirName) if f.startswith('image')]) #logfiles=GetLatestArchive('image*.jpg') latest_folder = report_dirName + latest_file(name_start='Z', name_end='') + '\\' image = cv.LoadImage( latest_folder + latest_file(path=latest_folder, name_start='Z', name_end='.tif'), cv.CV_LOAD_IMAGE_COLOR) # .jpg images are 4x times smaller #img = cv2.imread(latest_folder+latest_file(path=latest_folder, name_start='', name_end='.tif')) #gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #img2=cv2.equalizeHist(gray) #cvmat_img2=cv.fromarray(img2) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) newFrameImage8U = cv.CreateImage((image.width, image.height), cv.IPL_DEPTH_8U, 3) # optional convert to 8U cv.ConvertScale(image, newFrameImage8U) # optional image = newFrameImage8U # optional cv.PutText(image, "Counter:", (x, y), font, 255) #Draw the text #cv.PutText(cvmat_img2,"Counter:", (x,y),font, 255) cv.ShowImage('a_window', image) #Show the image #cv.Waitkey(10000) # open the latest xml-file in this folder and get the stage coordinates (x,y,z) (stage_x, stage_y, stage_z) = return_xyz_coordinates( latest_folder + latest_file(path=latest_folder, name_start='', name_end='.xml')) print 'stage coordinates x,y,z:', stage_x, stage_y, stage_z if cv.WaitKey(10) == 27: break cv.DestroyWindow("a_window")
def generate(ident, sp=SQ_SIZE): size = (Square.GRID_SIZE + 4) * sp img = cv.CreateImage((size, size), 8, 1) rim = [(0, 0), (size, 0), (size, size), (0, size)] border = [(sp, sp), (size - sp, sp), (size - sp, size - sp), (sp, size - sp)] inside = [(sp * 2, sp * 2), (sp * 5, sp * 2), (sp * 5, sp * 5), (sp * 2, sp * 5)] square = lambda (x, y): [((2 + x) * sp, (2 + y) * sp), ((3 + x) * sp, (2 + y) * sp), ((3 + x) * sp, (3 + y) * sp), ((2 + x) * sp, (3 + y) * sp)] corners = [square((0, 0))] #square(size-sp*2,sp*2), #square(size-sp*2,size-sp*2), square(sp*2,size-sp*2)] code = [] id = ident for p in Square.code_points: if ident % 2 == 0: code.append(square(p)) ident /= 2 cv.FillPoly(img, [rim], (255, 255, 255)) cv.FillPoly(img, [border], (0, 0, 0)) cv.FillPoly(img, [inside], (255, 255, 255)) cv.FillPoly(img, corners + code, (0, 0, 0)) font = cv.InitFont(cv.CV_FONT_HERSHEY_COMPLEX_SMALL, 0.7, 0.7) cv.PutText(img, "%d" % id, (0, 15), font, (50, 50, 50)) return img
def init(self, img, time_first=0, max_scale=0, flip_H=False, size=(640, 480), depth=8, channels=3): if img is not None: size, depth, channels, time_first = cv.GetSize( img), img.depth, img.nChannels, time_first self.imgs = imgs = [] self.gray_imgs = gray_imgs = [] self.tmp_imgs = tmp_imgs = [] self.canny_imgs = canny_imgs = [] self.bw_imgs = bw_imgs = [] self.draw_imgs = draw_imgs = [] db.m_d = self self.size, depth, channels, self.last = size, depth, channels, time_first wx, wy = self.size def image(wx, wy, d, c): return cv.CreateImage((wx, wy), d, c) for _ in range(max_scale + 1): for l in [imgs, draw_imgs]: l.append(image(wx, wy, depth, channels)) for l in [tmp_imgs, canny_imgs, bw_imgs, gray_imgs]: l.append(image(wx, wy, 8, 1)) wx, wy = wx / 2, wy / 2 self.scaled_images = zip( imgs, draw_imgs, tmp_imgs, canny_imgs, bw_imgs, gray_imgs) self.max_scale = max_scale self.font = cv.InitFont(cv.CV_FONT_HERSHEY_COMPLEX_SMALL, 0.7, 0.7) self.markers = {} self.processedRects = [] self.time = 0 self.not_found = [] self.flip_H = flip_H self.scale_factor = 1 self.set_scale(0)
def __init__(self, output_filename='sim.avi', draw_estimates=['cam1', 'cam2', 'kalman', 'average']): """ """ self._vidWriter = cv.CreateVideoWriter(output_filename, kc.codec, kc.fps, kc.img_size) self._draw_estimates = draw_estimates self._font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, .5, .5) (co,cw,cs) = (10,30,60) (w,h) = kc.img_size self.cam1center = (co, co) self.cam2center = (w-co, co) self.cam3center = (co, h-co) # status texts and stuffs: self.status_text = "" self.ball_coords = (0,0) self.cam1_estimate = (0,0) self.cam2_estimate = (0,0) self.cam3_estimate = (0,0) self.frame_num = 0
def setup(flipped, capture, thehandcolor): """Initializes camera and finds initial skin tone""" #creates initial window and prepares text color = (40, 0, 0) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0) textsize1 = (cv.GetSize(flipped)[0] / 2 - 150, cv.GetSize(flipped)[1] / 2 - 140) textsize2 = (cv.GetSize(flipped)[0] / 2 - 150, cv.GetSize(flipped)[1] / 2 - 110) point1 = (cv.GetSize(flipped)[0] / 2 - 25, cv.GetSize(flipped)[1] / 2 - 25) point2 = (cv.GetSize(flipped)[0] / 2 + 25, cv.GetSize(flipped)[1] / 2 + 25) #until Enter is pressed while (cv.WaitKey(10) != 10): #captures live video, and draws sub-box and text frame = cv.QueryFrame(capture) cv.Copy(frame, flipped) cv.Flip(flipped, flipped, 1) cv.Rectangle(flipped, point1, point2, color, 2) cv.PutText(flipped, "Put your hand in the box ", textsize1, font, color) cv.PutText(flipped, "and press enter", textsize2, font, color) cv.ShowImage("w2", flipped) #Creates sub-image inside box, and returns average color in box sub = cv.GetSubRect(flipped, (cv.GetSize(flipped)[0] / 2 - 25, cv.GetSize(flipped)[1] / 2 - 25, 50, 50)) cv.Set(thehandcolor, cv.Avg(sub)) return cv.Avg(sub)
def onNewFrame(frame):#use this to modify the image before printing frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) msg = "processed frame" font = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 1.0, 1.0) tsize, baseline = cv.GetTextSize(msg, font) h,w = frame.shape[:2] tpt = (w - tsize[0]) / 2, (h - tsize[1]) / 2
def pick_and_place(self): print "30 pick_and_place" n_piece = 0 while True and n_piece < 1: n_piece += 1 iteration = 0 angle = 0.0 # use Hough circles to find pieces and select one piece # "go to 19" next_piece, angle = self.hough_it(n_piece, iteration) error = 2 * self.piece_tolerance print print "Square number ", n_piece print "===============" # iterate to find next chess piece # if hunting to and fro accept error in position while error > self.piece_tolerance and iteration < 100: iteration += 1 next_piece, angle, error = self.chess_piece_iterate( n_piece, iteration, next_piece) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 1) position = (30, 60) s = "Tomando Piezas de ajedrez" cv.PutText(cv.fromarray(self.cv_image), s, position, font, self.white) msg = cv_bridge.CvBridge().cv2_to_imgmsg(self.cv_image, encoding="bgr8") self.pub.publish(msg)
def showWindow(message): print message print " [press any key to continue]" font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5) cv.PutText(image, message, (10, 20), font, cv.RGB(150, 150, 150)) cv.ShowImage('window', image) cv.WaitKey(10000)
class test_vision_node: def __init__(self): rospy.init_node('test_vision_node') """ Give the OpenCV display window a name. """ self.cv_window_name = "OpenCV Image" """ Create the window and make it re-sizeable (second parameter = 0) """ cv.NamedWindow(self.cv_window_name, 0) """ Create the cv_bridge object """ self.bridge = CvBridge() """ Subscribe to the raw camera image topic """ self.image_sub = rospy.Subscriber("/camera/image_raw", Image, self.callback) def callback(self, data): try: """ Convert the raw image to OpenCV format """ cv_image = self.bridge.imgmsg_to_cv(data, "bgr8") except CvBridgeError, e: print e """ Get the width and height of the image """ (width, height) = cv.GetSize(cv_image) """ Overlay some text onto the image display """ text_font = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 2, 2) cv.PutText(cv_image, "OpenCV Image", (50, height / 2), text_font, cv.RGB(255, 255, 0)) """ Refresh the image on the screen """ cv.ShowImage(self.cv_window_name, cv_image) cv.WaitKey(3)
def __init__(self, camno): self.camera = camno self.capture = None self.image = None self.cvfont = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 0.5, 0.5) self.xoffset = 0 self.yoffset = 0 self.dia = 10 self.stretch = 0 self.stroke = 1 self.serial = None #serial.Serial("/dev/ttyACM0") # key code assignment to function self.keys = { 1048603: self.quit, # ESC 1048608: self.drill, # SPACE 1048690: self.reset, # r 1376084: self.strokeminus, # 1376082: self.strokeplus, 1179476: self.stretchminus, 1179474: self.stretchplus, 1048621: self.diaminus, 1114155: self.diaplus, 1113938: self.crossup, 1113940: self.crossdown, 1113939: self.crossright, 1113937: self.crossleft }
def getHsvRange(self): self.x_co = 0 self.y_co = 0 cv.NamedWindow('camera feed', cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(1) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 1, 0, 2, 8) while True: src = cv.QueryFrame(capture) # src = cv.LoadImage('2012_automata.jpg') cv.Smooth(src, src, cv.CV_BLUR, 3) hsv = cv.CreateImage(cv.GetSize(src), src.depth, 3) cv.CvtColor(src, hsv, cv.CV_BGR2HSV) cv.SetMouseCallback("camera feed", self.on_mouse, 0) s = cv.Get2D(hsv, self.y_co, self.x_co) # print "H:", s[0], " S:", s[1], " V:", s[2] cv.PutText(src, str(s[0]) + "," + str(s[1]) + "," + str(s[2]), (self.x_co, self.y_co), font, (55, 25, 255)) cv.ShowImage("camera feed", src) if cv.WaitKey(10) == 27: return (s[0], s[1], s[2]) break
def __init__(self,topic=None): self.topic = topic self.lock = threading.Lock() self.bridge = CvBridge() rospy.init_node('zoom_tool') node_name = rospy.get_name() self.blobFinder = BlobFinder() self.blobFinder.threshold = rospy.get_param('/zoom_tool_params/threshold', 200) self.blobFinder.filter_by_area = rospy.get_param('/zoom_tool_params/filter_by_area', False) self.blobFinder.min_area = rospy.get_param('/zoom_tool_params/min_area', 0) self.blobFinder.max_area = rospy.get_param('/zoom_tool_params/max_area', 200) self.circle_color = (0,0,255) self.text_color = (0,0,255) self.cv_text_font = cv.InitFont(cv.CV_FONT_HERSHEY_TRIPLEX, 0.8, 0.8,thickness=1) self.image_sub = rospy.Subscriber(self.topic,Image,self.image_callback) self.image_pub = rospy.Publisher('image_zoom_tool', Image) #self.devel_pub = rospy.Publisher('develop', Float32) self.set_param_srv = rospy.Service( '{0}/set_param'.format(node_name), BlobFinderSetParam, self.handle_set_param_srv ) self.get_param_srv = rospy.Service( '{0}/get_param'.format(node_name), BlobFinderGetParam, self.handle_get_param_srv )
def draw_pizza(self): print "Number of boxes:", len(self.Boxes) for Box in self.Boxes: line_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) cv.Line(self.debug_frame, Box.corner1, Box.corner2, line_color, 10, cv.CV_AA, 0) cv.Line(self.debug_frame, Box.corner1, Box.corner3, line_color, 10, cv.CV_AA, 0) cv.Line(self.debug_frame, Box.corner3, Box.corner4, line_color, 10, cv.CV_AA, 0) cv.Line(self.debug_frame, Box.corner2, Box.corner4, line_color, 10, cv.CV_AA, 0) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 2, 1) cv.PutText(self.debug_frame, str("1"), (int(Box.corner1[0]), int(Box.corner1[1])), font, (0, 0, 255)) cv.PutText(self.debug_frame, str("2"), (int(Box.corner2[0]), int(Box.corner2[1])), font, (0, 0, 255)) cv.PutText(self.debug_frame, str("3"), (int(Box.corner3[0]), int(Box.corner3[1])), font, (0, 0, 255)) cv.PutText(self.debug_frame, str("4"), (int(Box.corner4[0]), int(Box.corner4[1])), font, (0, 0, 255)) center = (int(Box.center[0]), int(Box.center[1])) cv.Circle(self.debug_frame, center, 15, (255, 0, 0), 2, 8, 0)
def __init__(self, id=0, cap=None, width=None, height=None): """Create a new OpenCV Application""" self.storage = cv.CreateMemStorage(id) self.font = cv.InitFont(cv.CV_FONT_HERSHEY_PLAIN, 0.9, 0.9, 0, 1, 1) # Initialize capture device, if given if cap is not None and isinstance(cap, int): self.capture = OCVCapture(cap, width, height)
def sort_bins(self): # promote candidate to confirmed if seen enough times, if it hasn't been seen, delete the bin for candidate in self.candidates: candidate.last_seen -= 1 if candidate.last_seen < self.last_seen_thresh: self.candidates.remove(candidate) print "lost" continue if candidate.seencount > self.min_seencount: self.confirmed.append(candidate) self.candidates.remove(candidate) print "confirmed" continue self.min_perimeter = 500000 self.angles = [] for confirmed in self.confirmed: if 0 < line_distance(confirmed.corner1, confirmed.corner3) * 2 + line_distance(confirmed.corner1, confirmed.corner2) * 2 < self.min_perimeter: self.min_perimeter = line_distance(confirmed.corner1, confirmed.corner3) * 2 + line_distance(confirmed.corner1, confirmed.corner2) * 2 # print confirmed.angle/math.pi*180 self.angles.append(cv.Round(confirmed.angle / math.pi * 180 / 10) * 10) # compare perimeter of existing bins. If a bin is too much bigger than the others, it is deleted. This is done to get rid of bins found based of 3 bins for confirmed in self.confirmed: if math.fabs(line_distance(confirmed.corner1, confirmed.corner3) * 2 + math.fabs(line_distance(confirmed.corner1, confirmed.corner2) * 2) - self.min_perimeter) > self.min_perimeter * self.perimeter_threshold and line_distance(confirmed.corner1, confirmed.corner3) * 2 + line_distance(confirmed.corner1, confirmed.corner2) * 2 > self.min_perimeter: print "perimeter error (this is a good thing)" print math.fabs(line_distance(confirmed.corner1, confirmed.corner3) * 2 + math.fabs(line_distance(confirmed.corner1, confirmed.corner2) * 2) - self.min_perimeter), "is greater than", self.min_perimeter * self.perimeter_threshold print "yay?" confirmed.last_seen -= 5 continue confirmed.last_seen -= 1 if confirmed.last_seen < self.last_seen_thresh: self.confirmed.remove(confirmed) print "lost confirmed" continue # draw bins line_color = (confirmed.corner1[1] / 2, confirmed.corner2[1] / 2, confirmed.corner4[1] / 2) cv.Circle(self.debug_frame, (int(confirmed.midx), int(confirmed.midy)), 15, line_color, 2, 8, 0) pt1 = (cv.Round(confirmed.corner1[0]), cv.Round(confirmed.corner1[1])) pt2 = (cv.Round(confirmed.corner2[0]), cv.Round(confirmed.corner2[1])) cv.Line(self.debug_frame, pt1, pt2, line_color, 1, cv.CV_AA, 0) pt2 = (cv.Round(confirmed.corner2[0]), cv.Round(confirmed.corner2[1])) pt4 = (cv.Round(confirmed.corner4[0]), cv.Round(confirmed.corner4[1])) pt3 = (cv.Round(confirmed.corner3[0]), cv.Round(confirmed.corner3[1])) cv.Line(self.debug_frame, pt2, pt4, line_color, 1, cv.CV_AA, 0) cv.Line(self.debug_frame, pt3, pt4, line_color, 1, cv.CV_AA, 0) cv.Line(self.debug_frame, pt1, pt3, line_color, 1, cv.CV_AA, 0) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, .6, .6, 0, 1, 1) text_color = (0, 255, 0) # print id and last_seen by each bin cv.PutText(self.debug_frame, str(confirmed.id), (int(confirmed.midx), int(confirmed.midy)), font, confirmed.debug_color) cv.PutText(self.debug_frame, str(confirmed.last_seen), (int(confirmed.midx - 20), int(confirmed.midy - 20)), font, confirmed.debug_color)
def canny_it(self, iteration): print "24 canny_it" #called by 27# #called by 24 (iterative)# #called by 23# if self.save_images: # save raw image of chess board file_name = self.image_dir + "chess_board_" + str( iteration) + ".jpg" self.cv_image = self.cv_image cv.SaveImage(file_name, cv.fromarray(self.cv_image)) # create an empty image variable, the same dimensions as our camera feed. gray = cv.CreateImage((cv.GetSize(cv.fromarray(self.cv_image))), 8, 1) # convert the image to a grayscale image cv.CvtColor(cv.fromarray(self.cv_image), gray, cv.CV_BGR2GRAY) # display image on head monitor font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 1) position = (30, 60) cv.PutText(cv.fromarray(self.cv_image), "Buscando Tablero", position, font, self.white) msg = cv_bridge.CvBridge().cv2_to_imgmsg(self.cv_image, encoding="bgr8") self.pub.publish(msg) # create a canny edge detection map of the greyscale cv.Canny(gray, self.canny, self.canny_low, self.canny_high, 3) # display the canny transformation cv.ShowImage("Canny Edge Detection", self.canny) if self.save_images: # save Canny image of chess board file_name = self.image_dir + "canny_board_" + str( iteration) + ".jpg" cv.SaveImage(file_name, self.canny) # flood fill edge of image to leave only objects "go to 9" self.flood_fill_edge(self.canny) #//back from 9, "go to 8" chess_board_centre = self.look_for_chess_board(self.canny) #//back from 8 # 3ms wait cv.WaitKey(3) while chess_board_centre[0] == 0: if random.random() > 0.6: self.baxter_ik_move(self.limb, self.dither()) #"go to 24" (iterate) chess_board_centre = self.canny_it(iteration) #//back from 24 return chess_board_centre
def run(self): #initiate font font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) #instantiate images hsv_img=cv.CreateImage(cv.GetSize(cv.QueryFrame(self.capture)),8,3) threshold_img1 = cv.CreateImage(cv.GetSize(hsv_img),8,1) threshold_img1a = cv.CreateImage(cv.GetSize(hsv_img),8,1) threshold_img2 = cv.CreateImage(cv.GetSize(hsv_img),8,1) i=0 writer=cv.CreateVideoWriter(“angle_tracking.avi”,cv.CV_FOURCC(‘M’,’J’,’P’,’G’),30,cv.GetSize(hsv_img),1)
def text(self, text, x=0, y=0, step=15, font=None): """Draw text on image (Font will be stored and used by default until changed)""" if font is None: if self.font is None: font = self.font = cv.InitFont(cv.CV_FONT_HERSHEY_PLAIN, 0.9, 0.9, 0, 1, 1) else: self.font = font self.frame = OCVText(self.frame, text, x, y, step, self.font)
def __init__(self,text,bottomLeft,onClick,height=1,color=False): if not color: color = Colors.SILVER self.text = text self.font = cv.InitFont(cv.CV_FONT_HERSHEY_COMPLEX,0.75,0.75) self.bottomLeft = bottomLeft self.onClick = onClick self.status = DEFAULT CVPolygon.__init__(self,color,height,None)
def canny_it(self, iteration): ####图片格式转化################################# cv_image_trans = cv.fromarray(self.cv_image) #保存self.cv_image if self.save_images: # save raw image of ball tray file_name = self.image_dir + "ball_tray_" + str(iteration) + ".jpg" cv.SaveImage(file_name, self.cv_image) # create an empty image variable, the same dimensions as our camera feed. gray = cv.CreateImage((cv.GetSize(cv_image_trans)), 8, 1) # convert the image to a grayscale image #(src,dst,code) cv.CvtColor(cv_image_trans, gray, cv.CV_BGR2GRAY) # display image on head monitor font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 1) position = (30, 60) #cv.PutText(cv_image_trans, "Looking for ball tray", position, font, self.white) msg = cv_bridge.CvBridge().cv2_to_imgmsg(self.cv_image, encoding="bgr8") self.pub.publish(msg) # create a canny edge detection map of the greyscale image cv.Canny(gray, self.canny, self.canny_low, self.canny_high, 3) # display the canny transformation cv.ShowImage("Canny Edge Detection", self.canny) #保存self.canny if self.save_images: # save Canny image of ball tray file_name = self.image_dir + "canny_tray_" + str( iteration) + ".jpg" cv.SaveImage(file_name, self.canny) # flood fill edge of image to leave only objects self.flood_fill_edge(self.canny) ball_tray_centre = self.look_for_ball_tray(self.canny) #可能会返回(0,0) # 3ms wait cv.WaitKey(3) #第一次进来还未找到时起作用 while ball_tray_centre[0] == 0: if random.random() > 0.6: self.baxter_ik_move(self.limb, self.dither()) ball_tray_centre = self.canny_it(iteration) return ball_tray_centre
def set(self, set_name, card_name): self.card_name = card_name self.set_name = set_name self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, .5, .5) path = os.path.join(self.basedir, set_name, card_name+".full.jpg") try: self.img = cv.LoadImage(path) except IOError: return False return True
def __init__(self, *args): CalibrationNode.__init__(self, *args) cv.NamedWindow("display") self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.20, 1, thickness=2) #self.button = cv.LoadImage("%s/button.jpg" % roslib.packages.get_pkg_dir(PKG)) cv.SetMouseCallback("display", self.on_mouse) cv.CreateTrackbar("scale", "display", 0, 100, self.on_scale)
def getfont(self, **kwargs): '''get a font with some nice defaults''' fontsize = kwargs.pop('fontsize', 0.5) outline = kwargs.pop('outline', False) params = dict(font=CV_FONT_HERSHEY_PLAIN, hscale=fontsize*0.9, vscale=fontsize, shear=0, thickness=1, lineType=cv2.CV_AA) params.update(kwargs) if outline: params['thickess'] += 2 return cv.InitFont(**params)
def add_text(image, text, good = True): if good: color = (0, 255, 0) else: color = (0, 0, 255) w = image.cols h = image.rows for i in range(len(text)): font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.30, float(w)/350, thickness = 1) ((text_w, text_h), _) = cv.GetTextSize(text[i], font) cv.PutText(image, text[i], (w/2-text_w/2, h/2-text_h/2 + i*text_h*2), font, color) return image
def __init__(self, stereo, image, blob): global font rospy.Subscriber(blob, Blobs, callbackBlobs) rospy.Subscriber(stereo + "/left/" + image, Image, callbackImage) print "Subscribing to:" print "\t* " + blob print "\t* " + stereo + "/left/" + image cv.StartWindowThread() cv.NamedWindow(windowName) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.20, 1, thickness=2)
def find_squares(contours,sign): font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX,1,1,0,1,1) max_area = 1000 for i in contours: x,y,w,h = cv2.boundingRect(i) if (w*h > max_area and math.fabs(w-h) < 5 and y < 240): best = [x,y,w,h] try: cv.PutText(cv_image,sign,(best[0],best[1]),font,[0,0,255]) cv.Rectangle(cv_image,(best[0],best[1]),(best[0]+best[2],best[1]+best[3]),[0,0,255]) except UnboundLocalError: print sign," not found"
def __init__(self): self.startScreen = pygame.display.set_mode(imageSize, 0) self.redStick = Stick("red") self.blueStick = Stick("blue") self.currentHelpScreen = 1 self.videoFont = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) self.xFont = 800 self.yFont = 50 self.tom2Coords = (50, 450, 350, 650) self.tom1Coords = (375, 500, 675, 700) self.snareCoords = (700, 500, 1000, 700) self.hihatCoords = (900, 200, 1250, 400)