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()
python类CvBridge()的实例源码
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
inverse_perspective_mapping_node.py 文件源码
项目:autonomous_driving
作者: StatueFungus
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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()
publish_calib_file.py 文件源码
项目:camera_calibration_frontend
作者: groundmelon
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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"))
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")
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))
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)
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")
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")
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()
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...")
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...")
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...")
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...")
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())
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
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()
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)
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
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")
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 = []
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
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
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")
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)
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
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
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
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()
kalibr_camera_focus.py 文件源码
项目:camera_calibration_frontend
作者: groundmelon
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
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)