Python cv_bridge.CvBridgeError() Examples

The following are 30 code examples of cv_bridge.CvBridgeError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv_bridge , or try the search function .
Example #1
Source File: gCamera.py    From Cherry-Autonomous-Racecar with MIT License 7 votes vote down vote up
def gCamera():
    print "gstWebCam"
    bridge = CvBridge()
    video ="video4"
    pub = rospy.Publisher('stream', Image, queue_size=10)
    rospy.init_node('GstWebCam',anonymous=True)
    Gst.init(None)
    pipe = Gst.parse_launch("""v4l2src device=/dev/"""+video+""" ! video/x-raw, width=640, height=480,format=(string)BGR ! appsink sync=false max-buffers=2 drop=true name=sink emit-signals=true""")
    sink = pipe.get_by_name('sink')
    pipe.set_state(Gst.State.PLAYING)
    while not rospy.is_shutdown():
        sample = sink.emit('pull-sample')    
        img = gst_to_opencv(sample.get_buffer())
        try:
            pub.publish(bridge.cv2_to_imgmsg(img, "bgr8"))
        except CvBridgeError as e:
            print(e) 
Example #2
Source File: bagdump.py    From udacity-driving-reader with Apache License 2.0 7 votes vote down vote up
def write_image(bridge, outdir, msg, fmt='png'):
    results = {}
    image_filename = os.path.join(outdir, str(msg.header.stamp.to_nsec()) + '.' + fmt)
    try:
        if hasattr(msg, 'format') and 'compressed' in msg.format:
            buf = np.ndarray(shape=(1, len(msg.data)), dtype=np.uint8, buffer=msg.data)
            cv_image = cv2.imdecode(buf, cv2.IMREAD_ANYCOLOR)
            if cv_image.shape[2] != 3:
                print("Invalid image %s" % image_filename)
                return results
            results['height'] = cv_image.shape[0]
            results['width'] = cv_image.shape[1]
            # Avoid re-encoding if we don't have to
            if check_format(msg.data) == fmt:
                buf.tofile(image_filename)
            else:
                cv2.imwrite(image_filename, cv_image)
        else:
            cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")
            cv2.imwrite(image_filename, cv_image)
    except CvBridgeError as e:
        print(e)
    results['filename'] = image_filename
    return results 
Example #3
Source File: broadcaster_ros.py    From tf-pose-estimation with Apache License 2.0 6 votes vote down vote up
def callback_image(data):
    # et = time.time()
    try:
        cv_image = cv_bridge.imgmsg_to_cv2(data, "bgr8")
    except CvBridgeError as e:
        rospy.logerr('[tf-pose-estimation] Converting Image Error. ' + str(e))
        return

    acquired = tf_lock.acquire(False)
    if not acquired:
        return

    try:
        humans = pose_estimator.inference(cv_image, resize_to_default=True, upsample_size=resize_out_ratio)
    finally:
        tf_lock.release()

    msg = humans_to_msg(humans)
    msg.image_w = data.width
    msg.image_h = data.height
    msg.header = data.header

    pub_pose.publish(msg) 
Example #4
Source File: dataRecorder.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def depthCB(self, depth):
        if self.record == True:
            #rospy.loginfo("depth image recieved")
            try:
                grey = self.bridge.imgmsg_to_cv2(depth)
                rospy.loginfo(grey.dtype)

                if self.twist is not None:
                    fnamedepth = None
                    seq = str(depth.header.seq)
                    timestamp = str(depth.header.stamp)
                    with self.twistLock:
                        fnamedepth = seq + '_' + timestamp + '_' + str(round(self.twist.linear.x,8)) + '_' + str(round(self.twist.angular.z,8))
                    cv2.imwrite("/home/ubuntu/DepthIMG/"+fnamedepth+".tiff",grey)
            except CvBridgeError as x:
                print(x)
        else:
            rospy.loginfo("Not Recording Depth") 
Example #5
Source File: dataRecorder.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def lidargridCB(self, grid):
        if self.record == True:
            #rospy.loginfo("grid recieved")
            try:
                cv2lidarImg = self.bridge.imgmsg_to_cv2(grid)
                if self.twist is not None:
                    fnamelidar = None
                    timestamp = str(grid.header.stamp)
                    seq = str(grid.header.seq)
                    with self.twistLock:                  
                        fnamelidar = seq + '_' + timestamp + '_' + str(round(self.twist.linear.x,8)) + '_' + str(round(self.twist.angular.z,8))
                    cv2.imwrite("/home/ubuntu/LidarIMG/"+fnamelidar+".jpg",cv2lidarImg)
            except CvBridgeError as r:
                print(r)
        else:
            rospy.loginfo("Not Recording Lidar") 
Example #6
Source File: collector.py    From costar_plan with Apache License 2.0 6 votes vote down vote up
def _rgbCb(self, msg):
        if msg is None:
            rospy.logwarn("_rgbCb: msg is None !!!!!!!!!")
        try:
            # max out at 10 hz assuming 30hz data source
            if msg.header.seq % 3 == 0:
                cv_image = self._bridge.imgmsg_to_cv2(msg, "rgb8")
                # decode the data, this will take some time

                # rospy.loginfo('rgb color cv_image shape: ' + str(cv_image.shape) + ' depth sequence number: ' + str(msg.header.seq))
                # print('rgb color cv_image shape: ' + str(cv_image.shape))
                cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
                rgb_img = cv2.imencode('.jpg', cv_image)[1].tobytes()
                # rgb_img = GetJpeg(np.asarray(cv_image))

                with self.mutex:
                    self.rgb_time = msg.header.stamp
                    self.rgb_img = rgb_img
            #print(self.rgb_img)
        except CvBridgeError as e:
            rospy.logwarn(str(e)) 
Example #7
Source File: dataRecorder.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def streamCB(self, pic):
        if self.record == True:
            #rospy.loginfo("image recieved")
            try:
                cv2image = self.bridge.imgmsg_to_cv2(pic)
                if self.twist is not None:
                    fname = None
                    seq = str(pic.header.seq)
                    timestamp = str(pic.header.stamp)
                    with self.twistLock:
                        fname = seq + '_' + timestamp + '_' + str(round(self.twist.linear.x,8)) + '_' + str(round(self.twist.angular.z,8))
                    cv2.imwrite("/home/ubuntu/TrainingIMG/"+fname+".jpg",cv2image)
            except CvBridgeError as e:
                print(e)
        else:
            rospy.loginfo("Not Recording Webcam") 
Example #8
Source File: detect_crazyflie.py    From ROS-Robotics-By-Example with MIT License 6 votes vote down vote up
def depth_callback(self, msg):

      # create OpenCV depth image using defalut passthrough encoding
      try:
         depth_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='passthrough')
      except CvBridgeError as e:
         print(e)

      # using green ball (u, v) position, find depth value of Crazyflie point and divide by 1000
      # to change millimeters into meters (for Kinect sensors only)
      self.cf_d = depth_image[self.cf_v, self.cf_u] / 1000.0
      rospy.loginfo("Depth: x at %d  y at %d  z at %f", int(self.cf_u), int(self.cf_v), self.cf_d)

      # if depth value is zero, use the last non-zero depth value
      if self.cf_d == 0:
         self.cf_d = self.last_d
      else:
         self.last_d = self.cf_d

      # publish Crazyflie tf transform
      self.update_cf_transform (self.cf_u, self.cf_v, self.cf_d)


   # This function builds the Crazyflie base_link tf transform and publishes it. 
Example #9
Source File: omnirobot_server.py    From robotics-rl-srl with MIT License 6 votes vote down vote up
def imageCallback(self, msg):
        try:    
            # Convert your ROS Image message to OpenCV
            cv2_img = bridge.imgmsg_to_cv2(msg, "rgb8")
            
            if self.first_msg:
                shape = cv2_img.shape
                min_length = min(shape[0], shape[1])
                up_margin = int((shape[0] - min_length) / 2)  # row
                left_margin = int((shape[1] - min_length) / 2)  # col
                self.valid_box = [up_margin, up_margin + min_length, left_margin, left_margin + min_length]
                print("origin size: {}x{}".format(shape[0],shape[1]))
                print("crop each image to a square image, cropped size: {}x{}".format(min_length, min_length))
                self.first_msg = False
            
            undistort_image = cv2.undistort(cv2_img, self.camera_matrix, self.distortion_coefficients)
            self.valid_img = undistort_image[self.valid_box[0]:self.valid_box[1], self.valid_box[2]:self.valid_box[3]]

        except CvBridgeError as e:
            print("CvBridgeError:", e) 
Example #10
Source File: camera_subscriber.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 6 votes vote down vote up
def get_frames(self):
        cv_image = None
        depth_image = None
        while cv_image is None and depth_image is None:
            try:
                cv_image = self.bridge.imgmsg_to_cv2(self.rgb_raw, "bgr8")
            except CvBridgeError as e:
                print(e)

            try:
                depth_image_raw = self.bridge.imgmsg_to_cv2(self.depth_raw, "passthrough")
                # noinspection PyRedundantParentheses
                depth_image = ((255 * depth_image_raw)).astype(np.uint8)
            except CvBridgeError as e:
                print(e)

        if self.debug:
            print("Image has been converted.")

        return cv_image, depth_image 
Example #11
Source File: camera_node.py    From RacingRobot with MIT License 6 votes vote down vote up
def extractInfo(self):
        try:
            while not self.exit:
                try:
                    frame = self.frame_queue.get(block=True, timeout=1)
                except queue.Empty:
                    print("Queue empty")
                    continue
                try:
                    # Publish new image
                    msg = self.bridge.cv2_to_imgmsg(frame, 'rgb8')
                    if not self.exit:
                        self.image_publisher.publish(msg)
                except CvBridgeError as e:
                    print("Error Converting cv image: {}".format(e.message))
                self.frame_num += 1
        except Exception as e:
            print("Exception after loop: {}".format(e))
            raise 
Example #12
Source File: kinect2_sensor.py    From perception with Apache License 2.0 6 votes vote down vote up
def _process_image_msg(self, msg):
        """ Process an image message and return a numpy array with the image data
        Returns
        -------
        :obj:`numpy.ndarray` containing the image in the image message

        Raises
        ------
        CvBridgeError
            If the bridge is not able to convert the image
        """
        encoding = msg.encoding
        try:
            image = self._bridge.imgmsg_to_cv2(msg, encoding)
        except CvBridgeError as e:
            rospy.logerr(e)
        return image 
Example #13
Source File: real_robobo_server.py    From robotics-rl-srl with MIT License 5 votes vote down vote up
def imageCallback(self, msg):
        try:
            # Convert your ROS Image message to OpenCV
            cv2_img = bridge.imgmsg_to_cv2(msg, "rgb8")
            self.valid_img = cv2_img
        except CvBridgeError as e:
            print("CvBridgeError:", e) 
Example #14
Source File: cv_bridge_demo.py    From Learning-Robotics-using-Python-Second-Edition with MIT License 5 votes vote down vote up
def depth_callback(self, ros_image):
        # Use cv_bridge() to convert the ROS image to OpenCV format
        try:
            # The depth image is a single-channel float32 image
            depth_image = self.bridge.imgmsg_to_cv2(ros_image, "32FC1")
        except CvBridgeError, e:
            print e
	    pass
        # Convert the depth image to a Numpy array since most cv2 functions
        # require Numpy arrays. 
Example #15
Source File: manual.py    From image_recognition with MIT License 5 votes vote down vote up
def recognize_srv_callback(self, req):
        """
        Method callback for the Recognize.srv
        :param req: The service request
        """
        self._response.recognitions = []
        self._recognizing = True

        try:
            cv_image = self.bridge.imgmsg_to_cv2(req.image, "bgr8")
        except CvBridgeError as e:
            rospy.logerr(e)

        self._image_widget.set_image(cv_image)
        self._done_recognizing_button.setDisabled(False)

        timeout = 60.0  # Maximum of 60 seconds
        future = rospy.Time.now() + rospy.Duration(timeout)
        rospy.loginfo("Waiting for manual recognition, maximum of %d seconds", timeout)
        while not rospy.is_shutdown() and self._recognizing:
            if rospy.Time.now() > future:
                raise rospy.ServiceException("Timeout of %d seconds exceeded .." % timeout)
            rospy.sleep(rospy.Duration(0.1))

        self._done_recognizing_button.setDisabled(True)

        return self._response 
Example #16
Source File: gazebo_server.py    From robotics-rl-srl with MIT License 5 votes vote down vote up
def imageCallback(self, msg):
        try:
            # Convert your ROS Image message to OpenCV
            cv2_img = bridge.imgmsg_to_cv2(msg, "rgb8")
            self.valid_img = cv2_img
        except CvBridgeError as e:
            print("CvBridgeError:", e) 
Example #17
Source File: test.py    From image_recognition with MIT License 5 votes vote down vote up
def _image_callback(self, msg):
        """
        Sensor_msgs/Image callback
        :param msg: The image message
        """
        try:
            cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
        except CvBridgeError as e:
            rospy.logerr(e)
            return

        self._image_widget.set_image(cv_image) 
Example #18
Source File: real_baxter_server.py    From robotics-rl-srl with MIT License 5 votes vote down vote up
def imageCallback(self, msg):
        try:
            # Convert your ROS Image message to OpenCV
            cv2_img = bridge.imgmsg_to_cv2(msg, "rgb8")
            self.valid_img = cv2_img
        except CvBridgeError as e:
            print("CvBridgeError:", e) 
Example #19
Source File: utils.py    From rpg_public_dronet with MIT License 5 votes vote down vote up
def callback_img(data, target_size, crop_size, rootpath, save_img):
    try:
        image_type = data.encoding
        img = bridge.imgmsg_to_cv2(data, image_type)
    except CvBridgeError, e:
        print e 
Example #20
Source File: core.py    From pyrobot with MIT License 5 votes vote down vote up
def _sync_callback(self, rgb, depth):
        self.camera_img_lock.acquire()
        try:
            self.rgb_img = self.cv_bridge.imgmsg_to_cv2(rgb, "bgr8")
            self.rgb_img = self.rgb_img[:, :, ::-1]
            self.depth_img = self.cv_bridge.imgmsg_to_cv2(depth, "passthrough")
        except CvBridgeError as e:
            rospy.logerr(e)
        self.camera_img_lock.release() 
Example #21
Source File: annotation.py    From image_recognition with MIT License 5 votes vote down vote up
def _image_callback(self, msg):
        """
        Called when a new sensor_msgs/Image is coming in
        :param msg: The image messaeg
        """
        try:
            cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
        except CvBridgeError as e:
            rospy.logerr(e)

        self._image_widget.set_image(cv_image) 
Example #22
Source File: collector.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def _rgbdCb(self, rgb_msg, depth_msg):
        if rgb_msg is None:
            rospy.logwarn("_rgbdCb: rgb_msg is None !!!!!!!!!")
        try:
            # max out at 10 hz assuming 30hz data source
            # TODO(ahundt) make mod value configurable
            if rgb_msg.header.seq % 3 == 0:
                cv_image = self._bridge.imgmsg_to_cv2(rgb_msg, "rgb8")

                # decode the data, this will take some time

                rospy.loginfo('rgb color cv_image shape: ' + str(cv_image.shape) + ' depth sequence number: ' + str(msg.header.seq))
                # print('rgb color cv_image shape: ' + str(cv_image.shape))
                cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
                # encode the jpeg with high quality
                encode_params = [cv2.IMWRITE_JPEG_QUALITY, 99]
                rgb_img = cv2.imencode('.jpg', cv_image, encode_params)[1].tobytes()
                # rgb_img = GetJpeg(np.asarray(cv_image))

                cv_depth_image = self._bridge.imgmsg_to_cv2(depth_msg, desired_encoding="passthrough")
                depth_encoded_as_rgb_numpy = encode_depth_numpy(cv_depth_image)
                bytevalues = cv2.imencode('.png', depth_encoded_as_rgb_numpy)[1].tobytes()

                with self.mutex:
                    self.rgb_time = msg.header.stamp
                    self.rgb_img = rgb_img
                    # self.depth_info = depth_camera_info
                    # self.rgb_info = rgb_camera_info
                    self.depth_img_time = msg.header.stamp
                    # self.depth_img = np_image
                    # self.depth_img = img_str
                    self.depth_img = bytevalues
            #print(self.rgb_img)
        except CvBridgeError as e:
            rospy.logwarn(str(e)) 
Example #23
Source File: costar_hyper_prediction.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def _rgbCb(self, msg):
        if msg is None:
            rospy.logwarn("costar_hyper_prediction()::_rgbCb: msg is None !!!!!!!!!")
        try:
            # max out at 10 hz assuming 30hz data source
            if msg.header.seq % 3 == 0:
                cv_image = self._bridge.imgmsg_to_cv2(msg, "rgb8")
                # decode the data, this will take some time

                # rospy.loginfo('rgb color cv_image shape: ' + str(cv_image.shape) + ' depth sequence number: ' + str(msg.header.seq))
                # print('rgb color cv_image shape: ' + str(cv_image.shape))
                cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
                # Convert image to numpy format
                rgb_img = np.asarray(cv_image, dtype=np.uint8)
                # Resize to match what is expected of the neural network
                if self.image_shape is not None:
                    rgb_img = resize(rgb_img, self.image_shape, mode='constant', preserve_range=True)

                with self.mutex:
                    self.rgb_time = msg.header.stamp
                    # print('rgb_time stamp: ' + str(msg.header.stamp))
                    self.rgb_img = rgb_img
                    if self.need_clear_view_rgb_img or self.clear_view_rgb_img is None:
                        self.clear_view_rgb_img = rgb_img
                        self.clear_view_rgb_time = msg.header.stamp
                        self.need_clear_view_rgb_img = False

        except CvBridgeError as e:
            rospy.logwarn('costar_hyper_prediction.py Error converting image: ' + str(e)) 
Example #24
Source File: husky_test.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def imageCallback(data):
    
    try:
        # Convert your ROS Image message to OpenCV2
        cv2_img = bridge.imgmsg_to_cv2(data, "bgr8")
    except CvBridgeError, e:
        print(e) 
Example #25
Source File: tello_driver_node.py    From tello_driver with Apache License 2.0 5 votes vote down vote up
def framegrabber_loop(self):
        # Repeatedly try to connect
        vs = self.get_video_stream()
        while self.state != self.STATE_QUIT:
            try:
                container = av.open(vs)
                break
            except BaseException as err:
                rospy.logerr('fgrab: pyav stream failed - %s' % str(err))
                time.sleep(1.0)

        # Once connected, process frames till drone/stream closes
        while self.state != self.STATE_QUIT:
            try:
                # vs blocks, dies on self.stop
                for frame in container.decode(video=0):
                    img = np.array(frame.to_image())
                    try:
                        img_msg = self.bridge.cv2_to_imgmsg(img, 'rgb8')
                        img_msg.header.frame_id = rospy.get_namespace()
                    except CvBridgeError as err:
                        rospy.logerr('fgrab: cv bridge failed - %s' % str(err))
                        continue
                    self.pub_image_raw.publish(img_msg)
                break
            except BaseException as err:
                rospy.logerr('fgrab: pyav decoder failed - %s' % str(err)) 
Example #26
Source File: recorder.py    From ros-video-recorder with MIT License 5 votes vote down vote up
def callback_image(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError as e:
            rospy.logerr('[ros-video-recorder][VideoFrames] Converting Image Error. ' + str(e))
            return

        self.frames.append((time.time(), cv_image)) 
Example #27
Source File: recorder.py    From ros-video-recorder with MIT License 5 votes vote down vote up
def start_record(self):
        self.start_time = time.time()
        curr_time = self.start_time
        while self.end_time < 0 or curr_time <= self.end_time:
            try:
                canvas = np.zeros((self.output_height, self.output_width, 3), np.uint8)

                for frame_w in self.frame_wrappers:
                    f = frame_w.get_latest(at_time=curr_time)
                    if f is None:
                        continue

                    resized = cv2.resize(f, (frame_w.target_w, frame_w.target_h))
                    canvas[frame_w.target_y:frame_w.target_y+frame_w.target_h, frame_w.target_x:frame_w.target_x+frame_w.target_w] = resized
                    # rospy.sleep(0.01)

                if self.video_writer:
                    self.video_writer.write(canvas)
                if self.pub_img:
                    try:
                        self.pub_img.publish(self.bridge.cv2_to_imgmsg(canvas, 'bgr8'))
                    except CvBridgeError as e:
                        rospy.logerr('cvbridgeerror, e={}'.format(str(e)))
                        pass
                rospy.sleep(0.01)

                if rospy.is_shutdown() and self.end_time < 0:
                    self.terminate()

                while curr_time + self.interval > time.time():
                    rospy.sleep(self.interval)

                curr_time += self.interval
            except KeyboardInterrupt:
                self.terminate()
                continue

        if self.video_writer:
            self.video_writer.release() 
Example #28
Source File: visualization.py    From tf-pose-estimation with Apache License 2.0 5 votes vote down vote up
def callback_image(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError as e:
            rospy.logerr('Converting Image Error. ' + str(e))
            return

        self.frames.append((data.header.stamp, cv_image)) 
Example #29
Source File: camera_subscriber.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 5 votes vote down vote up
def callback(self, img, depth, debug=False):
    try:
      cv_image = self.bridge.imgmsg_to_cv2(img, "bgr8")
    except CvBridgeError as e:
      print(e)

    try:
      depth_image_raw = self.bridge.imgmsg_to_cv2(depth, "passthrough")
      depth_image = ((255 * depth_image_raw)).astype(np.uint8)
    except CvBridgeError as e:
      print(e)

    if self.debug:
      print("Image has been converted.")

    if not self.rgb_q.empty() and not self.depth_q.empty():
      if self.debug:
        print("Queue has item in it.")
      try:
        if self.debug:
          print("Attempting to remove item from queue.")
        self.rgb_q.get(False)
        self.depth_q.get(False)
        if self.debug:
          print("Successfully removed images from queue.")
      except:
        if self.debug:
          print("\033[91m"+"Exception Empty was raised. Could not remove from queue."+"\033[0m")

    if self.debug:
      print("Queue should be empty now, putting in images.")

    self.rgb_q.put(cv_image)
    self.depth_q.put(depth_image)

    if self.debug:
      print("Images are now in queue.") 
Example #30
Source File: color.py    From ros_book_programs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def callback(self, data):
        try:
            cv_image = self._bridge.imgmsg_to_cv2(data, 'bgr8')
        except CvBridgeError, e:
            print e