Python cv_bridge 模块,CvBridge() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv_bridge.CvBridge()

项目:geom_rcnn    作者:asbroad    | 项目源码 | 文件源码
def __init__(self):

        self.run_recognition = rospy.get_param('/rgb_object_detection/run_recognition')
        self.model_filename = rospy.get_param('/rgb_object_detection/model_file')
        self.weights_filename = rospy.get_param('/rgb_object_detection/weights_file')
        self.categories_filename = rospy.get_param('/rgb_object_detection/category_file')
        self.verbose = rospy.get_param('/rgb_object_detection/verbose', False)

        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber('/camera/rgb/image_color', Image, self.img_cb)
        self.patches_sub = rospy.Subscriber('/candidate_regions_depth', PolygonStamped, self.patches_cb)
        self.detection_pub = rospy.Publisher('/detections', Detection, queue_size=1)
        # you can read this value off of your sensor from the '/camera/depth_registered/camera_info' topic
        self.P = np.array([[525.0, 0.0, 319.5, 0.0], [0.0, 525.0, 239.5, 0.0], [0.0, 0.0, 1.0, 0.0]])

        if self.run_recognition:
            self.cnn = CNN('', self.model_filename, self.weights_filename, self.categories_filename, '', 0, 0, self.verbose)
            self.cnn.load_model()
项目:duo3d_ros    作者:ethz-ait    | 项目源码 | 文件源码
def extract_checkerboard_and_draw_corners(self, image, chbrd_size):
        image = CvBridge().imgmsg_to_cv2(image, 'mono8')
        image_color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
        ret, corners = cv2.findChessboardCorners(image_color, chbrd_size)

        if not ret:
            cv2.putText(image_color, 'Checkerboard not found', (0, self.res_height - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255))

        cv2.drawChessboardCorners(image_color, chbrd_size, corners, ret)

        return ret, corners, image_color
项目:autonomous_driving    作者:StatueFungus    | 项目源码 | 文件源码
def __init__(self, node_name, sub_topic, pub_topic):
        self.img_prep = ImagePreparator()
        self.bridge = CvBridge()

        self.camera = None
        self.horizon_y = None
        self.transformation_matrix = None
        self.image_resolution = DEFAULT_RESOLUTION
        self.transformated_image_resolution = DEFAULT_RESOLUTION

        self.image_pub = rospy.Publisher(pub_topic, Image, queue_size=QUEUE_SIZE)

        rospy.init_node(node_name, anonymous=True)

        self.image_sub = rospy.Subscriber(sub_topic, Image, self.callback)

        rospy.spin()
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def main(args):
    rospy.init_node("publish_calib_file", args)

    files = glob.glob("left-*.png");
    files.sort()

    print("All {} files".format(len(files)))

    image_pub = rospy.Publisher("image",Image, queue_size=10)
    bridge = CvBridge();


    for f in files:
        if rospy.is_shutdown():
            break
        raw_input("Publish {}?".format(f))
        img = cv2.imread(f, 0)
        image_pub.publish(bridge.cv2_to_imgmsg(img, "mono8"))
项目:intera_sdk    作者:RethinkRobotics    | 项目源码 | 文件源码
def _setup_image(self, image_path):
        """
        Load the image located at the specified path

        @type image_path: str
        @param image_path: the relative or absolute file path to the image file

        @rtype: sensor_msgs/Image or None
        @param: Returns sensor_msgs/Image if image convertable and None otherwise
        """
        if not os.access(image_path, os.R_OK):
            rospy.logerr("Cannot read file at '{0}'".format(image_path))
            return None

        img = cv2.imread(image_path)
        # Return msg
        return cv_bridge.CvBridge().cv2_to_imgmsg(img, encoding="bgr8")
项目:ros-video-recorder    作者:ildoonet    | 项目源码 | 文件源码
def __init__(self, output_width, output_height, output_fps, output_format, output_path):
        self.frame_wrappers = []
        self.start_time = -1
        self.end_time = -1
        self.pub_img = None
        self.bridge = CvBridge()

        self.fps = output_fps
        self.interval = 1.0 / self.fps
        self.output_width = output_width
        self.output_height = output_height

        if opencv_version() == 2:
            fourcc = cv2.cv.FOURCC(*output_format)
        elif opencv_version() == 3:
            fourcc = cv2.VideoWriter_fourcc(*output_format)
        else:
            raise

        self.output_path = output_path
        self.video_writer = cv2.VideoWriter(output_path, fourcc, output_fps, (output_width, output_height))
项目:AutonomousParking    作者:jovanduy    | 项目源码 | 文件源码
def __init__(self):
        """ Initialize the parking spot recognizer """

        #Subscribe to topics of interest
        rospy.Subscriber("/camera/image_raw", Image, self.process_image)
        rospy.Subscriber('/cmd_vel', Twist, self.process_twist)

        # Initialize video images
        cv2.namedWindow('video_window')        
        self.cv_image = None # the latest image from the camera
        self.dst =  np.zeros(IMG_SHAPE, np.uint8)
        self.arc_image = np.zeros(IMG_SHAPE, np.uint8)
        self.transformed = np.zeros(IMG_SHAPE, np.uint8)

        # Declare instance variables
        self.bridge = CvBridge() # used to convert ROS messages to OpenCV
        self.hsv_lb = np.array([0, 70, 60]) # hsv lower bound to filter for parking lines
        self.hsv_ub = np.array([30, 255, 140]) # hsv upper bound
        self.vel = None
        self.omega = None
        self.color = (0,0,255)
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def __init__(self, frame, transform_module=None):
        rospy.loginfo("Zarj eyes initialization begin")
        self.bridge = CvBridge()

        if transform_module is not None:
            self.tf = transform_module
        else:
            self.tf = tfzarj.TfZarj(rospy.get_param('/ihmc_ros/robot_name'))
            self.tf.init_transforms()

        self.detection_requests = []
        self.frame_id = frame

        self.image_sub_left = None
        self.image_sub_cloud = None

        rospy.loginfo("Zarj eyes initialization finished")
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def __init__(self):
        rospy.loginfo("Zarj eyes initialization begin")
        self.bridge = CvBridge()
        self.sub_left = None
        self.sub_right = None
        self.sub_cloud = None
        self.processors = []
        self.disabled = False
        self.left_image = None
        self.right_image = None
        self.cloud = None
        self.p_left = None
        self.cloud_image_count = 0
        self.info_sub_l = rospy.Subscriber(
            "/multisense/camera/left/camera_info", CameraInfo, self.info_left)

        rospy.loginfo("Zarj eyes initialization finished")
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def __init__(self):
        token = rospy.get_param('/telegram/token', None)
        if token is None:
            rospy.logerr("No token found in /telegram/token param server.")
            exit(0)
        else:
            rospy.loginfo("Got telegram bot token from param server.")

        # Set CvBridge
        self.bridge = CvBridge()

        # Create the EventHandler and pass it your bot's token.
        updater = Updater(token)

        # Get the dispatcher to register handlers
        dp = updater.dispatcher

        # on noncommand i.e message - echo the message on Telegram
        dp.add_handler(MessageHandler(Filters.text, self.pub_received))

        # log all errors
        dp.add_error_handler(self.error)

        # Start the Bot
        updater.start_polling()
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def __init__(self):
        self.node_name = "face_recog_fisher"
        rospy.init_node(self.node_name)

        rospy.on_shutdown(self.cleanup)
        self.bridge = CvBridge()
        self.face_names = StringArray()
        self.all_names = StringArray()

        self.size = 4
        face_haar = 'haarcascade_frontalface_default.xml'
        self.haar_cascade = cv2.CascadeClassifier(face_haar)
        self.face_dir = 'face_data_fisher'
        self.model = cv2.createFisherFaceRecognizer()
        # self.model = cv2.createEigenFaceRecognizer()

        (self.im_width, self.im_height) = (112, 92)        

        rospy.loginfo("Loading data...")
        # self.fisher_train_data()
        self.load_trained_data()
        rospy.sleep(3)        

        # self.img_sub = rospy.Subscriber("/asus/rgb/image_raw", Image, self.img_callback)
        self.img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback)

        # self.img_pub = rospy.Publisher('face_img', Image, queue_size=10)
        self.name_pub = rospy.Publisher('face_names', StringArray, queue_size=10)
        self.all_names_pub = rospy.Publisher('all_face_names', StringArray, queue_size=10)
        rospy.loginfo("Detecting faces...")
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def __init__(self):
        self.node_name = "train_faces_eigen"
        rospy.init_node(self.node_name)

        rospy.on_shutdown(self.cleanup)
        self.bridge = CvBridge()

        self.size = 4
        face_haar = 'haarcascade_frontalface_default.xml'
        self.haar_cascade = cv2.CascadeClassifier(face_haar)
        self.face_dir = 'face_data_eigen'
        self.face_name = sys.argv[1]
        self.path = os.path.join(self.face_dir, self.face_name)
        # self.model = cv2.createFisherFaceRecognizer()
        self.model = cv2.createEigenFaceRecognizer()

        self.cp_rate = 5

        if not os.path.isdir(self.path):
            os.mkdir(self.path)

        self.count = 0    

        self.train_img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback)
        # self.train_img_pub = rospy.Publisher('train_face', Image, queue_size=10)
        rospy.loginfo("Capturing data...")
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def __init__(self):
        self.node_name = "hand_gestures"
        rospy.init_node(self.node_name)

        rospy.on_shutdown(self.cleanup)

        # self.cv_window_name = self.node_name
        # cv2.namedWindow("Depth Image", 1)
        # cv2.moveWindow("Depth Image", 20, 350)

        self.bridge = CvBridge()
        self.numFingers = RecognizeNumFingers() 

        self.depth_sub = rospy.Subscriber("/asus/depth/image_raw", Image, self.depth_callback)
        self.num_pub = rospy.Publisher('num_fingers', Int32, queue_size=10, latch=True)       
        # self.img_pub = rospy.Publisher('hand_img', Image, queue_size=10)
        rospy.loginfo("Waiting for image topics...")
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def __init__(self):
        self.node_name = "train_faces_fisher"
        rospy.init_node(self.node_name)

        rospy.on_shutdown(self.cleanup)
        self.bridge = CvBridge()

        self.size = 4
        face_haar = 'haarcascade_frontalface_default.xml'
        self.haar_cascade = cv2.CascadeClassifier(face_haar)
        self.face_dir = 'face_data_fisher'
        self.face_name = sys.argv[1]
        self.path = os.path.join(self.face_dir, self.face_name)
        self.model = cv2.createFisherFaceRecognizer()
        # self.model = cv2.createEigenFaceRecognizer()

        self.cp_rate = 5

        if not os.path.isdir(self.path):
            os.mkdir(self.path)

        self.count = 0    

        self.train_img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback)
        # self.train_img_pub = rospy.Publisher('train_face', Image, queue_size=10)
        rospy.loginfo("Capturing data...")
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def test_object_image_serializer(self):
        """Tests object image serializer can be deserialized."""
        # Create random 40 x 30 RGB image.
        width = 40
        height = 30
        nparr = np.random.randint(0, 256, (width, height, 3)).astype(np.uint8)

        # Convert to ROS Image.
        bridge = CvBridge()
        msg = bridge.cv2_to_imgmsg(nparr)

        # Serialize.
        png = serializers.ObjectImageSerializer.from_msg(msg)

        # Deserialize.
        converted_msg = serializers.ObjectImageSerializer.from_raw(png)

        # Convert to array.
        converted_img = bridge.imgmsg_to_cv2(converted_msg)
        converted_arr = np.asarray(converted_img)

        # Test if we get the original image.
        self.assertTrue((converted_arr == nparr).all())
项目:diy_driverless_car_ROS    作者:wilselby    | 项目源码 | 文件源码
def __init__(self):

      """ROS Subscriptions """
      self.image_sub = rospy.Subscriber("/raspicam_node/image/image_raw",Image,self.cvt_image) 
      self.image_pub = rospy.Publisher("/image_converter/output_video",Image, queue_size=10)
      self.cmdVel_pub = rospy.Publisher("/platform_control/cmd_vel", Twist, queue_size=10)
      self.cmdVelStamped_pub = rospy.Publisher('/platform_control/cmd_vel_stamped', TwistStamped, queue_size=10)

      """ Variables """
      self.model_path = 'home/wil/ros/catkin_ws/src/diy_driverless_car_ROS/rover_ml/behavior_cloning/src/behavior_cloning/model.h5'
      self.cmdvel = Twist()
      self.baseVelocity = TwistStamped()
      self.bridge = CvBridge()
      self.latestImage = None
      self.outputImage = None
      self.resized_image = None
      self.imgRcvd = False
项目:curly-fortnight    作者:sManohar201    | 项目源码 | 文件源码
def __init__(self):
        self.bridge = cv_bridge.CvBridge()
        cv2.namedWindow("input", 1)
        cv2.createTrackbar('param1', 'input', 10, 300, nothing)
        cv2.createTrackbar('param2', 'input', 15, 300, nothing)
        cv2.namedWindow("processed", 1)
        self.image_sb = rospy.Subscriber('/usb_cam/image_raw', Image, self.image_callback)

        self.motion = Twist()

        rate = rospy.Rate(20)

        # publish to cmd_vel of the jackal
        pub = rospy.Publisher("/jackal_velocity_controller/cmd_vel", Twist, queue_size=10)

        while not rospy.is_shutdown():
            # publish Twist
            pub.publish(self.motion)
            rate.sleep()
项目:baxter_gui    作者:HumaRobotics    | 项目源码 | 文件源码
def grabImage(self,camera_name,filename):
        """
            Grabs exactly one image from a camera

            :param camera_name: The image of the camera that should be saved
            :type camera_name: str
            :param filename: The full path of the filename where this image should be saved
            :type filename: str 
        """
        if self.open(camera_name) != 0:
            return
        msg=rospy.wait_for_message('/cameras/' + camera_name + "/image", Image)        
        img = cv_bridge.CvBridge().imgmsg_to_cv2(msg, "bgr8")
        cv2.imwrite(filename,img)
        rospy.loginfo("Saved Image %s"%filename)
        self.close(camera_name)
项目:duo3d_ros    作者:ethz-ait    | 项目源码 | 文件源码
def vio_sensor_cb(data):
    global cnt, active, imgs
    num_samples = 100  # number of image samples to take

    if cnt == num_samples and active:
        imgs['l'] /= num_samples
        imgs['r'] /= num_samples
        active = 0
        return

    left = np.float32(CvBridge().imgmsg_to_cv2(data.left_image, "mono8"))
    right = np.float32(CvBridge().imgmsg_to_cv2(data.right_image, "mono8"))

    if cnt == 0:
        imgs['l'] = left
        imgs['r'] = right
    else:
        cv2.accumulate(left, imgs['l'])
        cv2.accumulate(right, imgs['r'])

    cnt += 1
项目:TA_example_labs    作者:mit-racecar    | 项目源码 | 文件源码
def __init__(self):

        self.detector = Detector()
        self.sub_image = rospy.Subscriber("/camera/rgb/image_rect_color", Image, self.processImage, queue_size=1)
        self.pub_image = rospy.Publisher("detection_image", Image, queue_size=1)
        self.bridge = CvBridge()

        rospy.loginfo("Object Detector Initialized.")

        self.drive_cmd = {'steer': 0, 'speed': 0}

        self.pub_detection = rospy.Publisher("object_detection",\
                Detection, queue_size=1)

        #self.pub = rospy.Publisher("/vesc/ackermann_cmd_mux/input/navigation",\
        #        AckermannDriveStamped, queue_size =1 )
        #self.thread = Thread(target=self.drive)
        #self.thread.start()
        rospy.loginfo("Detector initialized")
项目:unrealcv-ros    作者:jskinn    | 项目源码 | 文件源码
def __init__(self, config):
        host = unrealcv.HOST
        port = unrealcv.PORT

        if 'endpoint' in config:
            host, port = config['endpoint']
        if 'port' in config:
            port = config['port']
        if 'hostname' in config:
            host = config['hostname']

        self.opencv_bridge = cv_bridge.CvBridge()

        self._client_lock = threading.Lock()
        self._client = unrealcv.Client(endpoint=(host, port))
        self._client.connect()
        if not self._client.isconnected():
            raise RuntimeError("Could not connect to unrealcv simulator, is it running?")

        # Store the declare services
        self._services = []
项目:unrealcv-ros    作者:jskinn    | 项目源码 | 文件源码
def __init__(self, config):
        host = unrealcv.HOST
        port = unrealcv.PORT

        if 'endpoint' in config:
            host, port = config['endpoint']
        if 'port' in config:
            port = config['port']
        if 'hostname' in config:
            host = config['hostname']

        self.opencv_bridge = cv_bridge.CvBridge()

        self._client_lock = threading.Lock()
        self._client = unrealcv.Client(endpoint=(host, port))
        self._client.connect()
        if not self._client.isconnected():
            raise RuntimeError("Could not connect to unrealcv simulator, is it running?")

        # Service attributes
        self._get_camera_view_service = None
项目:Face-Recognition-for-Mobile-Robot    作者:gagolucasm    | 项目源码 | 文件源码
def __init__(self):

        global et
    global recognizer
    global dictid, labels
        self.engine1 = pyttsx.init()
    self.engine = pyttsx.init()
    self.engine1.say('Initializing components.         All systems ready.')
        self.engine1.runAndWait()
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("/camera/rgb/image_raw",Image,self.callback)
    recognizer = cv2.face.createLBPHFaceRecognizer()
    et = libs.EyeTracker("cascades/haarcascade_frontalface_alt2.xml")
    i=0
    path = 'faces'
    images,labels,dictid=libs.read_data(path)
    print labels
    recognizer.train(images, np.array(labels))
    print 'termine'
    self.num=0
项目:racecar_7    作者:karennguyen    | 项目源码 | 文件源码
def __init__(self):
        self.bridge = CvBridge() #allows us to convert our image to cv2

        self.zed_pub = rsp.Publisher("/image_echo", Image, queue_size = 1)
        self.imginfo_pub = rsp.Publisher("/exploring_challenge", img_info, queue_size = 1)

        self.zed_img = rsp.Subscriber("/camera/rgb/image_rect_color", Image, self.detect_img) #subscribes to the ZED camera image
        self.odom_sub = rsp.Subscriber("/vesc/odom", Odometry, self.odom_callback)

        self.last_arb_position = Point()
        self.gone_far_enough = True

        self.header = std_msgs.msg.Header()
        self.heightThresh = 75 #unit pixels MUST TWEAK
        self.odomThresh = 1 #unit meters
        self.blob_msg = img_info()

        rsp.init_node("vision_node")
项目:shell_game    作者:BlakeStrebel    | 项目源码 | 文件源码
def __init__(self):
        self.bridge = CvBridge()
        # initializes subscriber for Baxter's left hand camera image topic
        self.image_sub = rospy.Subscriber("/cameras/left_hand_camera/image",Image,self.find_cups)
        # initializes subscriber for the location of the treasure (published by the find_treasure node)
        self.treasure_location_sub = rospy.Subscriber("/treasure_location",Treasure,self.find_treasure)
        # initializes publisher to publish the location of the cup containing the treasure
        self.treasure_cup_pub = rospy.Publisher("treasure_cup_location",Point,queue_size=10)
        # initializes publisher to publish the processed image to Baxter's display
        self.image_tracking_pub = rospy.Publisher("/robot/xdisplay",Image,queue_size=10)
        self.treasure_cup_location = Point()
        self.cups = []
        self.cupCenters = [[0,0],[0,0],[0,0]]
        self.wasPreviouslyTrue = False
        self.flag = False
        self.minRadius = 10
        for i in range(0,3):
            self.cups.append(cup())

    # determines the location of the 3 red cups (callback for the image topic subscriber)
项目:baxter    作者:destrygomorphous    | 项目源码 | 文件源码
def make_mask(limb, filename):

    """
    Given a limb (right or left) and a name to save to
    (in the baxter_tools/share/images/ directory),
    create a mask of any dark objects in the image from the camera
    and save it.
    """

    image_sub = rospy.Subscriber(
        '/cameras/' + limb + '_hand_camera/image',Image,callback)


    try:
        bridge = CvBridge()
        cv_image = bridge.imgmsg_to_cv2(img, "bgr8")
    except CvBridgeError, e:
        print e

    msk = cv2.threshold(img, 250, 255, cv2.THRESH_BINARY_INV)
    return msk
项目:formulapi_ROS_simulator    作者:wilselby    | 项目源码 | 文件源码
def __init__(self):
      self.imgprocess = ImageProcessor.ImageProcessor()
      self.bridge = CvBridge()
      self.latestimage = None
      self.process = False

      """ROS Subscriptions """
      self.image_pub = rospy.Publisher("/image_converter/output_video",Image, queue_size=10)
      self.image_sub = rospy.Subscriber("/cam/camera_/image_raw",Image,self.cvt_image)
      self.cmdVelocityPub = rospy.Publisher('/platform_control/cmd_vel', Twist, queue_size=10)

      self.targetlane = 0
      self.cmdvel = Twist()
      self.last_time = rospy.Time()
      self.sim_time = rospy.Time()
      self.dt = 0
      self.position_er = 0
      self.position_er_last = 0;
      self.cp = 0
      self.vel_er = 0
      self.cd = 0
      self.Kp = 3
      self.Kd = 3.5
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def __init__(self, channel='/camera/rgb/image_raw', every_k_frames=1, scale=1., encoding='bgr8', compressed=False): 
        Decoder.__init__(self, channel=channel, every_k_frames=every_k_frames)
        self.scale = scale
        self.encoding = encoding
        self.bridge = CvBridge()
        self.compressed = compressed
项目:ab2016-ros-gazebo    作者:akademikbilisim    | 项目源码 | 文件源码
def __init__(self, name):
        self.name = name

        # Publisher
        self.cmd_vel = rospy.Publisher("/%s/cmd_vel" % self.name,
                                       Twist, queue_size=1)

        # Subscriber
        self.odom = rospy.Subscriber("/%s/odom" % self.name,
                                     Odometry, self.odom_callback,
                                     queue_size=1)

        self.laser = rospy.Subscriber("/%s/front_laser/scan" % self.name,
                                      LaserScan, self.laser_callback,
                                      queue_size=1)

        self.camera = rospy.Subscriber("/%s/front_camera/image_raw" % self.name,
                                       Image, self.camera_callback,
                                       queue_size=1)

        self.pose_data = None
        self.laser_data = None
        self.camera_data = None

        self.cv_bridge = cv_bridge.CvBridge()

        self.rate = rospy.Rate(10)
        self.rate.sleep()
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def __init__(self, topic):
        self.topic = topic
        self.windowNameOrig = "Camera: {0}".format(self.topic)
        cv2.namedWindow(self.windowNameOrig, 2)
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber(self.topic, Image, self.callback)
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def __init__(self, boards, flags=0, pattern=Patterns.Chessboard, name='', checkerboard_flags=cv2.CALIB_CB_FAST_CHECK):
        # Ordering the dimensions for the different detectors is actually a minefield...
        if pattern == Patterns.Chessboard:
            # Make sure n_cols > n_rows to agree with OpenCV CB detector output
            self._boards = [ChessboardInfo(max(i.n_cols, i.n_rows), min(i.n_cols, i.n_rows), i.dim) for i in boards]
        elif pattern == Patterns.ACircles:
            # 7x4 and 4x7 are actually different patterns. Assume square-ish pattern, so n_rows > n_cols.
            self._boards = [ChessboardInfo(min(i.n_cols, i.n_rows), max(i.n_cols, i.n_rows), i.dim) for i in boards]
        elif pattern == Patterns.Circles:
            # We end up having to check both ways anyway
            self._boards = boards

        # Set to true after we perform calibration
        self.calibrated = False
        self.calib_flags = flags
        self.checkerboard_flags = checkerboard_flags
        self.pattern = pattern
        self.br = cv_bridge.CvBridge()

        # self.db is list of (parameters, image) samples for use in calibration. parameters has form
        # (X, Y, size, skew) all normalized to [0,1], to keep track of what sort of samples we've taken
        # and ensure enough variety.
        self.db = []
        # For each db sample, we also record the detected corners.
        self.good_corners = []
        # Set to true when we have sufficiently varied samples to calibrate
        self.goodenough = False
        self.param_ranges = [0.7, 0.7, 0.4, 0.5]
        self.name = name

        self.accu_image = None
项目:geom_rcnn    作者:asbroad    | 项目源码 | 文件源码
def __init__(self):
        self.data_dir = rospy.get_param('/store_data/data_dir')
        self.category = rospy.get_param('/store_data/category')
        self.pic_count = rospy.get_param('/store_data/init_idx')
        self.rate = 1/float(rospy.get_param('/store_data/rate'))

        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber('/camera/rgb/image_color', Image, self.img_cb)
        self.patches_sub = rospy.Subscriber('/candidate_regions_depth', PolygonStamped, self.patches_cb)
        self.capture_sub = rospy.Subscriber('/capture/keyboard', Bool, self.capture_cb)
        # you can read this value off of your sensor from the '/camera/depth_registered/camera_info' topic
        self.P = np.array([[525.0, 0.0, 319.5, 0.0], [0.0, 525.0, 239.5, 0.0], [0.0, 0.0, 1.0, 0.0]])

        self.capture = False
项目:nimo    作者:wolfram2012    | 项目源码 | 文件源码
def ImgCcallback(self, ros_img):
        global imgi
        imgi = mx.img.imdecode(ros_img.data)
        global img_rect
        global img_raw
        global Frame
        img_rect = CvBridge().compressed_imgmsg_to_cv2(ros_img)
        # img_raw = img_rect.copy()

        Frame = pv.Image(img_rect.copy())
        # cv2.imshow("tester", Frame.asOpenCV())

    # def Imgcallback(self, ros_img):
    #     global img_rect
    #     img_rect = CvBridge().imgmsg_to_cv2(ros_img)
项目:nimo    作者:wolfram2012    | 项目源码 | 文件源码
def DepthImgcallback(self, ros_img):
        global img_depth
        img_depth = CvBridge().imgmsg_to_cv2(ros_img)
        # cv2.imshow("tester", img_depth)


    # def trackCallback(event):
    #     print "1"
项目:image_recognition    作者:tue-robotics    | 项目源码 | 文件源码
def __init__(self, context):
        """
        :param context: QT context, aka parent
        """
        super(FolderImagePublisherPlugin, self).__init__(context)

        # Widget setup
        self.setObjectName('FolderImagePublisherPlugin')

        self._widget = QWidget()
        context.add_widget(self._widget)

        # Layout and attach to widget
        layout = QHBoxLayout()
        self._widget.setLayout(layout)

        self._info = QLineEdit()
        self._info.setDisabled(True)
        self._info.setText("Please choose a directory (top-right corner)")
        layout.addWidget(self._info)

        self._left_button = QPushButton('<')
        self._left_button.clicked.connect(partial(self._rotate_and_publish, -1))
        layout.addWidget(self._left_button)

        self._right_button = QPushButton('>')
        self._right_button.clicked.connect(partial(self._rotate_and_publish, 1))
        layout.addWidget(self._right_button)

        # Set subscriber and service to None
        self._pub = rospy.Publisher("folder_image", Image, queue_size=1)

        self._bridge = CvBridge()

        self._files = collections.deque([])
项目:image_recognition    作者:tue-robotics    | 项目源码 | 文件源码
def __init__(self, context):
        """
        TestPlugin class to evaluate the image_recognition_msgs interfaces
        :param context: QT context, aka parent
        """
        super(TestPlugin, self).__init__(context)

        # Widget setup
        self.setObjectName('Test Plugin')

        self._widget = QWidget()
        context.add_widget(self._widget)

        # Layout and attach to widget
        layout = QVBoxLayout()  
        self._widget.setLayout(layout)

        self._image_widget = ImageWidget(self._widget, self.image_roi_callback, clear_on_click=True)
        layout.addWidget(self._image_widget)

        # Input field
        grid_layout = QGridLayout()
        layout.addLayout(grid_layout)

        self._info = QLineEdit()
        self._info.setDisabled(True)
        self._info.setText("Draw a rectangle on the screen to perform recognition of that ROI")
        layout.addWidget(self._info)

        # Bridge for opencv conversion
        self.bridge = CvBridge()

        # Set subscriber and service to None
        self._sub = None
        self._srv = None
项目:micros_mars_task_alloc    作者:liminglong    | 项目源码 | 文件源码
def __init__(self, node_name, receive_topic, send_topic, virtual_off= None):
        FunctionUnit.__init__(self, node_name)    
        self._receive_topic = receive_topic
        self._send_topic = send_topic
        self._virtual = virtual_off
        self.br = CvBridge()
        self._virtual_send = FunctionUnit.create_send(self, virtual_off, Bool)
项目:ros-video-recorder    作者:ildoonet    | 项目源码 | 文件源码
def __init__(self, image_topic, target_x, target_y, target_w, target_h):
        self.image_sub = rospy.Subscriber(image_topic, Image, self.callback_image, queue_size=1)
        self.bridge = CvBridge()
        self.frames = []
        self.target_x, self.target_y, self.target_w, self.target_h = target_x, target_y, target_w, target_h
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def __init__(self, prefix=None, color_range=None):
        rospy.loginfo("Zarj eyes initialization begin")
        self.bridge = CvBridge()
        self.prefix = prefix
        self.color_range = None
        if color_range:
            self.color_range = (
                np.array(color_range[0]),
                np.array(color_range[1])
            )

        self.image_sub_left = None
        self.image_sub_right = None

        rospy.loginfo("Zarj eyes initialization finished")
项目:openface_ros    作者:schelian    | 项目源码 | 文件源码
def __init__(self, align_path, net_path, storage_folder):
        self._bridge = CvBridge()
        self._learn_srv = rospy.Service('learn', LearnFace, self._learn_face_srv)
        self._detect_srv = rospy.Service('detect', DetectFace, self._detect_face_srv)
        self._clear_srv = rospy.Service('clear', Empty, self._clear_faces_srv)

        # Init align and net
        self._align = openface.AlignDlib(align_path)
        self._net = openface.TorchNeuralNet(net_path, imgDim=96, cuda=False)
        self._face_detector = dlib.get_frontal_face_detector()

        self._face_dict = {}  # Mapping from string to list of reps

        self._face_dict_filename = rospy.get_param( '~face_dict_filename', '' )
        if ( self._face_dict_filename != '' ):
          if ( not os.path.isfile( self._face_dict_filename ) ):
            print '_face_dict does not exist; will save to %s' % self._face_dict_filename
          else:
            with open( self._face_dict_filename, 'rb') as f:
              self._face_dict = pickle.load( f )
              print 'read _face_dict: %s' % self._face_dict_filename

        if not os.path.exists(storage_folder):
            os.makedirs(storage_folder)

        self._storage_folder = storage_folder
项目:gazebo_python_examples    作者:erlerobot    | 项目源码 | 文件源码
def __init__(self):
    self.bridge = CvBridge()
    self.x = 0.0
    self.y = 0.0
    self.ang = 0.0
    self.pos_sub = rospy.Subscriber("/slam_out_pose", PoseStamped, self.pos_callback)
    self.image_sub = rospy.Subscriber("/map_image/full",Image,self.img_callback)
项目:gazebo_python_examples    作者:erlerobot    | 项目源码 | 文件源码
def __init__(self):

    self.bridge = CvBridge()
    self.pub = rospy.Publisher('/mavros/rc/override', OverrideRCIn, queue_size=10)
    self.image_sub = rospy.Subscriber("/rover/front/image_front_raw",Image,self.callback)
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def __init__(self):
        token = rospy.get_param('/telegram/token', None)
        if token is None:
            rospy.logerr("No token found in /telegram/token param server.")
            exit(0)
        else:
            rospy.loginfo("Got telegram bot token from param server.")

        # Set CvBridge
        self.bridge = CvBridge()

        # Create the EventHandler and pass it your bot's token.
        updater = Updater(token)

        # Get the dispatcher to register handlers
        dp = updater.dispatcher

        # on message...
        dp.add_handler(MessageHandler(Filters.text, self.pub_received))
        dp.add_handler(CallbackQueryHandler(self.button))

        # log all errors
        dp.add_error_handler(self.error)

        # Start the Bot
        updater.start_polling()
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def __init__(self):
        self.node_name = "move_tbot"
        rospy.init_node(self.node_name)

        rospy.on_shutdown(self._shutdown)

        self.bridge = CvBridge()
        self.turn = Twist()
        self.move = GoToPose()
        # self.face_recog_file = FaceRecognition()
        # self.get_person_data = GetPersonData()
        self.qr_data = []
        self.all_face_names = []
        self.face_names = []
        self.counter = 0

        self.qr_sub = rospy.Subscriber('ar_pose_marker', AlvarMarkers, self.qr_callback)
        self.odom_sub = rospy.Subscriber('odom', Odometry, self.odom_callback)
        self.num_fingers_sub = rospy.Subscriber('num_fingers', Int32, self.num_fingers_callback)
        # self.hand_img_sub = rospy.Subscriber('hand_img', Image, self.hand_img_callback)
        # self.face_img_sub = rospy.Subscriber('face_img', Image, self.face_img_callback)
        self.face_name_sub = rospy.Subscriber('face_names', StringArray, self.face_names_callback)
        self.all_face_names_sub = rospy.Subscriber('all_face_names', StringArray, self.all_face_names_callback)

        self.turn_pub = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10)
        self.rate = rospy.Rate(10)

        while not rospy.is_shutdown():
            self.run_tbot_routine()
项目:andruinoR2    作者:andruino    | 项目源码 | 文件源码
def __init__(self):
    self.bridge = cv_bridge.CvBridge()
    cv2.namedWindow("window", 1)
    self.image_sub = rospy.Subscriber('camera/rgb/image_raw', 
                                      Image, self.image_callback)
项目:andruinoR2    作者:andruino    | 项目源码 | 文件源码
def __init__(self):
    self.bridge = cv_bridge.CvBridge()
    cv2.namedWindow("window", 1)
    self.image_sub = rospy.Subscriber('camera/rgb/image_raw', 
                                      Image, self.image_callback)
    self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop',
                                       Twist, queue_size=1)
    self.twist = Twist()
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def test_object_image(self):
        """Tests posting telemetry data through client."""
        # Set up test data.
        url = "http://interop"
        client_args = (url, "testuser", "testpass", 1.0)
        object_id = 1

        width = 40
        height = 30
        nparr = np.random.randint(0, 256, (width, height, 3)).astype(np.uint8)

        bridge = CvBridge()
        ros_img = bridge.cv2_to_imgmsg(nparr)

        img = ObjectImageSerializer.from_msg(ros_img)

        with InteroperabilityMockServer(url) as server:
            # Setup mock server.
            server.set_root_response()
            server.set_login_response()
            server.set_post_object_image_response(object_id)
            server.set_get_object_image_response(object_id, img, "image/png")
            server.set_delete_object_image_response(object_id)

            # Connect client.
            client = InteroperabilityClient(*client_args)
            client.wait_for_server()
            client.login()
            client.post_object_image(object_id, ros_img)
            client.get_object_image(object_id)
            client.delete_object_image(object_id)
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def from_msg(cls, msg):
        """Serializes a ROS Image message into a compressed PNG image.

        Args:
            msg: ROS Image or CompressedImage message.

        Returns:
            Compressed PNG image.

        Raises:
            CvBridgeError: On image conversion error.
        """
        if isinstance(msg, CompressedImage):
            # Decompress message.
            msg = cls.from_raw(msg.data)

        # Convert ROS Image to OpenCV image.
        bridge = CvBridge()
        img = bridge.imgmsg_to_cv2(msg)

        # Convert to PNG with highest level of compression to limit bandwidth
        # usage. PNG is used since it is a lossless format, so this can later
        # be retrieved as a ROS image without issue.
        compression = [cv2.IMWRITE_PNG_COMPRESSION, 9]
        png = cv2.imencode(".png", img, compression)[1].tostring()

        return png
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def from_raw(cls, raw, compress=False):
        """Deserializes binary-encoded image data into a ROS Image message.

        Args:
            raw: Binary encoded image data.
            compress: Whether to return a compressed image or not.

        Returns:
            ROS Image or CompressedImage message.

        Raises:
            CvBridgeError: On image conversion error.
        """
        # Convert to OpenCV image.
        nparr = np.fromstring(raw, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        # Convert to ROS message.
        bridge = CvBridge()
        msg = bridge.cv2_to_imgmsg(img)

        if compress:
            data = cls.from_msg(msg)
            msg = CompressedImage()
            msg.format = "png"
            msg.data = data

        return msg
项目:diy_driverless_car_ROS    作者:wilselby    | 项目源码 | 文件源码
def __init__(self):

      """ROS Subscriptions """
      self.image_pub = rospy.Publisher("/image_converter/output_video",Image, queue_size=10)
      self.image_sub = rospy.Subscriber("/raspicam_node/image/image_raw",Image,self.cvt_image) 
      self.cmdVelocityPub = rospy.Publisher('/platform_control/cmd_vel', Twist, queue_size=10)
      self.cmdVelocityStampedPub = rospy.Publisher('/platform_control/cmd_vel_stamped', TwistStamped, queue_size=10)

      """ Variables """
      self.bridge = CvBridge()
      self.latestImage = None
      self.outputImage = None
      self.blurImage = None
      self.edgeImage = None
      self.maskedImage = None
      self.lineMarkedImage = None
      self.imgRcvd = False

      self.kernel_size = 11
      self.low_threshold = 40
      self.high_threshold = 50
      self.rho = 1
      self.theta = np.pi/180
      self.threshold = 100
      self.min_line_len = 60
      self.max_line_gap = 80
      self.lines = (0, 0, 0, 0)

      self.intersectionPoint = (0,  0)  
      self.speed = 0.2
      self.flag = 0