code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if isinstance(content, pathlib.Path):
if not mimetype:
mimetype = guess_type(content.name)[0]
with content.open('rb') as fp:
content = fp.read()
else:
if isinstance(content, text_type):
content = content.encode('utf8')
return "data:{0};base64,... | def data_url(content, mimetype=None) | Returns content encoded as base64 Data URI.
:param content: bytes or str or Path
:param mimetype: mimetype for
:return: str object (consisting only of ASCII, though)
.. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme | 2.141962 | 2.341712 | 0.914699 |
if PY3: # pragma: no cover
return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)
return binary_type(s) | def to_binary(s, encoding='utf8') | Portable cast function.
In python 2 the ``str`` function which is used to coerce objects to bytes does not
accept an encoding argument, whereas python 3's ``bytes`` function requires one.
:param s: object to be converted to binary_type
:return: binary_type instance, representing s. | 3.41252 | 4.428472 | 0.770586 |
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in iteritems(kw):
if f(v):
d[k] = v
return d | def dict_merged(d, _filter=None, **kw) | Update dictionary d with the items passed as kw if the value passes _filter. | 3.300447 | 3.280133 | 1.006193 |
invalid = list(range(0x9))
invalid.extend([0xb, 0xc])
invalid.extend(range(0xe, 0x20))
return re.sub('|'.join('\\x%0.2X' % i for i in invalid), '', text) | def xmlchars(text) | Not all of UTF-8 is considered valid character data in XML ...
Thus, this function can be used to remove illegal characters from ``text``. | 3.99477 | 4.06838 | 0.981907 |
res = ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
if lowercase:
res = res.lower()
for c in string.punctuation:
res = res.replace(c, '')
res = re.sub('\s+', '' if remove_whitespace else ' ', res)
res = res.encode('ascii... | def slug(s, remove_whitespace=True, lowercase=True) | Condensed version of s, containing only lowercase alphanumeric characters. | 2.39986 | 2.38567 | 1.005948 |
assert isinstance(string, string_types) or isinstance(string, binary_type)
if isinstance(string, text_type):
return string.encode(encoding)
try:
# make sure the string can be decoded in the specified encoding ...
string.decode(encoding)
return string
except UnicodeDe... | def encoded(string, encoding='utf-8') | Cast string to binary_type.
:param string: six.binary_type or six.text_type
:param encoding: encoding which the object is forced to
:return: six.binary_type | 3.846063 | 4.28606 | 0.897342 |
if comment:
strip = True
if isinstance(p, (list, tuple)):
res = [l.decode(encoding) if encoding else l for l in p]
else:
with Path(p).open(encoding=encoding or 'utf-8') as fp:
res = fp.readlines()
if strip:
res = [l.strip() or None for l in res]
if co... | def readlines(p,
encoding=None,
strip=False,
comment=None,
normalize=None,
linenumbers=False) | Read a `list` of lines from a text file.
:param p: File path (or `list` or `tuple` of text)
:param encoding: Registered codec.
:param strip: If `True`, strip leading and trailing whitespace.
:param comment: String used as syntax to mark comment lines. When not `None`, \
commented lines will be stri... | 2.100386 | 2.180654 | 0.963191 |
for dirpath, dirnames, filenames in os.walk(as_posix(p), **kw):
if mode in ('all', 'dirs'):
for dirname in dirnames:
yield Path(dirpath).joinpath(dirname)
if mode in ('all', 'files'):
for fname in filenames:
yield Path(dirpath).joinpath(fn... | def walk(p, mode='all', **kw) | Wrapper for `os.walk`, yielding `Path` objects.
:param p: root of the directory tree to walk.
:param mode: 'all|dirs|files', defaulting to 'all'.
:param kw: Keyword arguments are passed to `os.walk`.
:return: Generator for the requested Path objects. | 2.08201 | 2.113132 | 0.985272 |
m = max(itertools.chain(map(len, self), [0]))
fields = (" %s = {%s}" % (k.ljust(m), self[k]) for k in self)
return "@%s{%s,\n%s\n}" % (
getattr(self.genre, 'value', self.genre), self.id, ",\n".join(fields)) | def bibtex(self) | Represent the source in BibTeX format.
:return: string encoding the source in BibTeX syntax. | 4.681001 | 4.969867 | 0.941877 |
genre = getattr(self.genre, 'value', self.genre)
pages_at_end = genre in (
'book',
'phdthesis',
'mastersthesis',
'misc',
'techreport')
thesis = genre in ('phdthesis', 'mastersthesis')
if self.get('editor'):
... | def text(self) | Linearize the bib source according to the rules of the unified style.
Book:
author. year. booktitle. (series, volume.) address: publisher.
Article:
author. year. title. journal volume(issue). pages.
Incollection:
author. year. title. In editor (ed.), booktitle, pages. ... | 3.045892 | 3.01156 | 1.0114 |
response_text = self._get_http_client(type).request(path, method, params)
if not response_text:
return response_text
response_json = json.loads(response_text)
if 'errors' in response_json:
raise (ErrorException([Error().load(e) for e in response_json['... | def request(self, path, method='GET', params=None, type=REST_TYPE) | Builds a request, gets a response and decodes it. | 3.520015 | 3.532767 | 0.99639 |
return HLR().load(self.request('hlr', 'POST', {'msisdn': msisdn, 'reference': reference})) | def hlr_create(self, msisdn, reference) | Perform a new HLR lookup. | 5.189696 | 4.997866 | 1.038382 |
if params is None: params = {}
if type(recipients) == list:
recipients = ','.join(recipients)
params.update({'originator': originator, 'body': body, 'recipients': recipients})
return Message().load(self.request('messages', 'POST', params)) | def message_create(self, originator, recipients, body, params=None) | Create a new message. | 3.242727 | 3.14038 | 1.032591 |
if params is None: params = {}
if type(recipients) == list:
recipients = ','.join(recipients)
params.update({'recipients': recipients, 'body': body})
return VoiceMessage().load(self.request('voicemessages', 'POST', params)) | def voice_message_create(self, recipients, body, params=None) | Create a new voice message. | 3.699452 | 3.635488 | 1.017594 |
if params is None: params = {}
return Lookup().load(self.request('lookup/' + str(phonenumber), 'GET', params)) | def lookup(self, phonenumber, params=None) | Do a new lookup. | 8.265169 | 8.007254 | 1.03221 |
if params is None: params = {}
return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'GET', params)) | def lookup_hlr(self, phonenumber, params=None) | Retrieve the information of a specific HLR lookup. | 6.343312 | 4.962026 | 1.278371 |
if params is None: params = {}
return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'POST', params)) | def lookup_hlr_create(self, phonenumber, params=None) | Perform a new HLR lookup. | 5.702344 | 5.231503 | 1.090001 |
if params is None: params = {}
params.update({'recipient': recipient})
return Verify().load(self.request('verify', 'POST', params)) | def verify_create(self, recipient, params=None) | Create a new verification. | 6.212423 | 5.289098 | 1.174571 |
return Verify().load(self.request('verify/' + str(id), params={'token': token})) | def verify_verify(self, id, token) | Verify the token of a specific verification. | 12.004441 | 9.714843 | 1.23568 |
items = []
for item in value:
items.append(self.itemType().load(item))
self._items = items | def items(self, value) | Create typed objects from the dicts. | 5.300447 | 4.605425 | 1.150914 |
if params is None: params = {}
url = urljoin(self.endpoint, path)
headers = {
'Accept': 'application/json',
'Authorization': 'AccessKey ' + self.access_key,
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
... | def request(self, path, method='GET', params=None) | Builds a request and gets a response. | 1.613026 | 1.601535 | 1.007175 |
config_h = opj("src", "cysignals", "cysignals_config.h")
if not os.path.isfile(config_h):
import subprocess
subprocess.check_call(["make", "configure"])
subprocess.check_call(["sh", "configure"])
dist = self.distribution
ext_modules = dist.ex... | def run(self) | Run ``./configure`` and Cython first. | 4.68738 | 3.809688 | 1.230384 |
# Search all subdirectories of sys.path directories for a
# "cython_debug" directory. Note that sys_path is a variable set by
# cysignals-CSI. It may differ from sys.path if GDB is run with a
# different Python interpreter.
files = []
for path in sys_path: # noqa
pattern = os.path.... | def cython_debug_files() | Cython extra debug information files | 8.028732 | 7.690939 | 1.043921 |
running = self._webcam.start()
if not running:
return running
running &= self._phoxi.start()
if not running:
self._webcam.stop()
return running | def start(self) | Start the sensor. | 6.545506 | 6.461855 | 1.012945 |
# Check that everything is running
if not self._running:
logging.warning('Colorized PhoXi not running. Aborting stop')
return False
self._webcam.stop()
self._phoxi.stop()
return True | def stop(self) | Stop the sensor. | 11.482861 | 11.340666 | 1.012538 |
_, phoxi_depth_im, _ = self._phoxi.frames()
webcam_color_im, _, _ = self._webcam.frames(most_recent=True)
# Colorize PhoXi Image
phoxi_color_im = self._colorize(phoxi_depth_im, webcam_color_im)
return phoxi_color_im, phoxi_depth_im, None | def frames(self) | Retrieve a new frame from the PhoXi and convert it to a ColorImage,
a DepthImage, and an IrImage.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the current frame. | 4.793262 | 3.814715 | 1.256519 |
depths = []
for _ in range(num_img):
_, depth, _ = self.frames()
depths.append(depth)
median_depth = Image.median_images(depths)
median_depth.data[median_depth.data == 0.0] = fill_depth
return median_depth | def median_depth_img(self, num_img=1, fill_depth=0.0) | Collect a series of depth images and return the median of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
DepthImage
The median DepthImage collected from the frames. | 3.2683 | 3.420025 | 0.955636 |
# Project the point cloud into the webcam's frame
target_shape = (depth_im.data.shape[0], depth_im.data.shape[1], 3)
pc_depth = self._phoxi.ir_intrinsics.deproject(depth_im)
pc_color = self._T_webcam_world.inverse().dot(self._T_phoxi_world).apply(pc_depth)
# Sort the po... | def _colorize(self, depth_im, color_im) | Colorize a depth image from the PhoXi using a color image from the webcam.
Parameters
----------
depth_im : DepthImage
The PhoXi depth image.
color_im : ColorImage
Corresponding color image.
Returns
-------
ColorImage
A colori... | 2.815706 | 2.757844 | 1.020981 |
sensor_type = sensor_type.lower()
if sensor_type == 'kinect2':
s = Kinect2Sensor(packet_pipeline_mode=cfg['pipeline_mode'],
device_num=cfg['device_num'],
frame=cfg['frame'])
elif sensor_type == 'bridged_kinect2':
... | def sensor(sensor_type, cfg) | Creates a camera sensor of the specified type.
Parameters
----------
sensor_type : :obj:`str`
the type of the sensor (real or virtual)
cfg : :obj:`YamlConfig`
dictionary of parameters for sensor initialization | 2.534265 | 2.589846 | 0.978539 |
inds = np.where(np.linalg.norm(point - all_points, axis=1) < eps)
if inds[0].shape[0] == 0:
return -1
return inds[0][0] | def get_point_index(point, all_points, eps = 1e-4) | Get the index of a point in an array | 2.052876 | 2.029287 | 1.011624 |
if not isinstance(source_obj_features, f.BagOfFeatures):
raise ValueError('Must supply source bag of object features')
if not isinstance(target_obj_features, f.BagOfFeatures):
raise ValueError('Must supply target bag of object features')
# source feature descrip... | def match(self, source_obj_features, target_obj_features) | Matches features between two graspable objects based on a full distance matrix.
Parameters
----------
source_obj_features : :obj:`BagOfFeatures`
bag of the source objects features
target_obj_features : :obj:`BagOfFeatures`
bag of the target objects features
... | 2.726534 | 2.648036 | 1.029644 |
# compute the distances and inner products between the point sets
dists = ssd.cdist(source_points, target_points, 'euclidean')
ip = source_normals.dot(target_normals.T) # abs because we don't have correct orientations
source_ip = source_points.dot(target_normals.T)
targe... | def match(self, source_points, target_points, source_normals, target_normals) | Matches points between two point-normal sets. Uses the closest ip to choose matches, with distance for thresholding only.
Parameters
----------
source_point_cloud : Nx3 :obj:`numpy.ndarray`
source object points
target_point_cloud : Nx3 :obj:`numpy.ndarray`
target... | 2.662332 | 2.658699 | 1.001367 |
self._cfg.enable_device(self.id)
# configure the color stream
self._cfg.enable_stream(
rs.stream.color,
RealSenseSensor.COLOR_IM_WIDTH,
RealSenseSensor.COLOR_IM_HEIGHT,
rs.format.bgr8,
RealSenseSensor.FPS
)
# ... | def _config_pipe(self) | Configures the pipeline to stream color and depth. | 2.886195 | 2.564033 | 1.125647 |
sensor = self._profile.get_device().first_depth_sensor()
self._depth_scale = sensor.get_depth_scale() | def _set_depth_scale(self) | Retrieve the scale of the depth sensor. | 4.951019 | 3.307539 | 1.496889 |
strm = self._profile.get_stream(rs.stream.color)
obj = strm.as_video_stream_profile().get_intrinsics()
self._intrinsics[0, 0] = obj.fx
self._intrinsics[1, 1] = obj.fy
self._intrinsics[0, 2] = obj.ppx
self._intrinsics[1, 2] = obj.ppy | def _set_intrinsics(self) | Read the intrinsics matrix from the stream. | 2.245258 | 2.073849 | 1.082652 |
return CameraIntrinsics(
self._frame,
self._intrinsics[0, 0],
self._intrinsics[1, 1],
self._intrinsics[0, 2],
self._intrinsics[1, 2],
height=RealSenseSensor.COLOR_IM_HEIGHT,
width=RealSenseSensor.COLOR_IM_WIDTH,
... | def color_intrinsics(self) | :obj:`CameraIntrinsics` : The camera intrinsics for the RealSense color camera. | 3.109635 | 2.600459 | 1.195802 |
try:
self._depth_align = False
if self._registration_mode == RealSenseRegistrationMode.DEPTH_TO_COLOR:
self._depth_align = True
self._config_pipe()
self._profile = self._pipe.start(self._cfg)
# store intrinsics and depth scal... | def start(self) | Start the sensor. | 5.438458 | 5.170919 | 1.051739 |
# check that everything is running
if not self._running:
logging.warning('Realsense not running. Aborting stop.')
return False
self._pipe.stop()
self._running = False
return True | def stop(self) | Stop the sensor. | 7.371281 | 6.711824 | 1.098253 |
frames = self._pipe.wait_for_frames()
if self._depth_align:
frames = self._align.process(frames)
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
logging.warning('Could not retr... | def _read_color_and_depth_image(self) | Read a color and depth image from the device. | 2.201262 | 2.169411 | 1.014682 |
self._cap = cv2.VideoCapture(self._device_id + cv2.CAP_V4L2)
if not self._cap.isOpened():
self._running = False
self._cap.release()
self._cap = None
return False
self._cap.set(cv2.CAP_PROP_FRAME_WIDTH, self._camera_intr.width)
sel... | def start(self) | Start the sensor. | 2.844753 | 2.736228 | 1.039663 |
# Check that everything is running
if not self._running:
logging.warning('Webcam not running. Aborting stop')
return False
if self._cap:
self._cap.release()
self._cap = None
self._running = False
return True | def stop(self) | Stop the sensor. | 4.919415 | 4.733197 | 1.039343 |
if most_recent:
for i in xrange(4):
self._cap.grab()
for i in range(1):
if self._adjust_exposure:
try:
command = 'v4l2-ctl -d /dev/video{} -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=100 -c satur... | def frames(self, most_recent=False) | Retrieve a new frame from the PhoXi and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
most_recent: bool
If true, the OpenCV buffer is emptied for the webcam before reading the most recent frame.
Returns
-------
:obj:... | 3.169447 | 3.040336 | 1.042466 |
num_points = msg.height * msg.width
self._format = '<' + num_points * 'ffff' | def _set_format(self, msg) | Set the buffer formatting. | 10.109334 | 9.439609 | 1.070948 |
focal_x = msg.K[0]
focal_y = msg.K[4]
center_x = msg.K[2]
center_y = msg.K[5]
im_height = msg.height
im_width = msg.width
self._camera_intr = CameraIntrinsics(self._frame, focal_x, focal_y,
center_x, center_y,
... | def _set_camera_properties(self, msg) | Set the camera intrinsics from an info msg. | 2.152053 | 1.9232 | 1.118996 |
# set format
if self._format is None:
self._set_format(msg)
# rescale camera intr in case binning is turned on
if msg.height != self._camera_intr.height:
rescale_factor = float(msg.height) / self._camera_intr.height
self._camera_intr = self._... | def _depth_im_from_pointcloud(self, msg) | Convert a pointcloud2 message to a depth image. | 3.532671 | 3.390183 | 1.04203 |
# initialize subscribers
self._pointcloud_sub = rospy.Subscriber('/%s/depth/points' %(self.frame), PointCloud2, self._pointcloud_callback)
self._camera_info_sub = rospy.Subscriber('/%s/left/camera_info' %(self.frame), CameraInfo, self._camera_info_callback)
while self._camera_i... | def start(self) | Start the sensor | 3.458929 | 3.530439 | 0.979745 |
# check that everything is running
if not self._running:
logging.warning('Ensenso not running. Aborting stop')
return False
# stop subs
self._pointcloud_sub.unregister()
self._camera_info_sub.unregister()
self._running = False
ret... | def stop(self) | Stop the sensor | 7.836547 | 7.234614 | 1.083202 |
# wait for a new image
while self._cur_depth_im is None:
time.sleep(0.01)
# read next image
depth_im = self._cur_depth_im
color_im = ColorImage(np.zeros([depth_im.height,
depth_im.width,
... | def frames(self) | Retrieve a new frame from the Ensenso and convert it to a ColorImage,
a DepthImage, and an IrImage.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the current frame.
... | 3.853102 | 3.917681 | 0.983516 |
pass | def register(self, source_point_cloud, target_point_cloud,
source_normal_cloud, target_normal_cloud, matcher,
num_iterations=1, compute_total_cost=True, match_centroids=False,
vis=False) | Iteratively register objects to one another.
Parameters
----------
source_point_cloud : :obj:`autolab_core.PointCloud`
source object points
target_point_cloud : :obj`autolab_core.PointCloud`
target object points
source_normal_cloud : :obj:`autolab_core.No... | 5,167.578613 | 17,300.777344 | 0.298691 |
if not self._running:
raise RuntimeError('Device pointing to %s not runnning. Cannot read frames' %(self._path_to_images))
if self._im_index >= self._num_images:
raise RuntimeError('Device is out of images')
# read images
color_filename = os.path.join(s... | def frames(self) | Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`... | 3.183703 | 2.681106 | 1.187459 |
depths = []
for _ in range(num_img):
_, depth, _ = self.frames()
depths.append(depth)
return Image.median_images(depths) | def median_depth_img(self, num_img=1) | Collect a series of depth images and return the median of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The median DepthImage collected from the frames. | 5.562636 | 6.022546 | 0.923635 |
if not self._running:
raise RuntimeError('Device pointing to %s not runnning. Cannot read frames' %(self._path_to_images))
if self._im_index >= self._num_images:
raise RuntimeError('Device is out of images')
# read images
datapoint = self._dataset.datap... | def frames(self) | Retrieve the next frame from the tensor dataset and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`,... | 3.650934 | 3.151394 | 1.158514 |
return CameraIntrinsics(self._ir_frame, PrimesenseSensor.FOCAL_X, PrimesenseSensor.FOCAL_Y,
PrimesenseSensor.CENTER_X, PrimesenseSensor.CENTER_Y,
height=PrimesenseSensor.DEPTH_IM_HEIGHT,
width=PrimesenseSens... | def color_intrinsics(self) | :obj:`CameraIntrinsics` : The camera intrinsics for the primesense color camera. | 4.334641 | 3.602277 | 1.203306 |
# open device
openni2.initialize(PrimesenseSensor.OPENNI2_PATH)
self._device = openni2.Device.open_any()
# open depth stream
self._depth_stream = self._device.create_depth_stream()
self._depth_stream.configure_mode(PrimesenseSensor.DEPTH_IM_WIDTH,
... | def start(self) | Start the sensor | 2.232473 | 2.230704 | 1.000793 |
# check that everything is running
if not self._running or self._device is None:
logging.warning('Primesense not running. Aborting stop')
return False
# stop streams
if self._depth_stream:
self._depth_stream.stop()
if self._color_stre... | def stop(self) | Stop the sensor | 4.639801 | 4.430437 | 1.047256 |
# read raw uint16 buffer
im_arr = self._depth_stream.read_frame()
raw_buf = im_arr.get_buffer_as_uint16()
buf_array = np.array([raw_buf[i] for i in range(PrimesenseSensor.DEPTH_IM_WIDTH * PrimesenseSensor.DEPTH_IM_HEIGHT)])
# convert to image in meters
depth_ima... | def _read_depth_image(self) | Reads a depth image from the device | 3.461277 | 3.47287 | 0.996662 |
# read raw buffer
im_arr = self._color_stream.read_frame()
raw_buf = im_arr.get_buffer_as_triplet()
r_array = np.array([raw_buf[i][0] for i in range(PrimesenseSensor.COLOR_IM_WIDTH * PrimesenseSensor.COLOR_IM_HEIGHT)])
g_array = np.array([raw_buf[i][1] for i in r... | def _read_color_image(self) | Reads a color image from the device | 1.911005 | 1.930692 | 0.989803 |
color_im = self._read_color_image()
depth_im = self._read_depth_image()
return color_im, depth_im, None | def frames(self) | Retrieve a new frame from the Kinect and convert it to a ColorImage,
a DepthImage, and an IrImage.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the current frame.
... | 4.176788 | 5.031694 | 0.830096 |
depths = []
for _ in range(num_img):
_, depth, _ = self.frames()
depths.append(depth)
return Image.min_images(depths) | def min_depth_img(self, num_img=1) | Collect a series of depth images and return the min of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The min DepthImage collected from the frames. | 5.652231 | 6.335126 | 0.892205 |
rospy.wait_for_service(stream_buffer, timeout = self.timeout)
ros_image_buffer = rospy.ServiceProxy(stream_buffer, ImageBuffer)
ret = ros_image_buffer(number, 1)
if not staleness_limit == None:
if ret.timestamps[-1] > staleness_limit:
raise R... | def _ros_read_images(self, stream_buffer, number, staleness_limit = 10.) | Reads images from a stream buffer
Parameters
----------
stream_buffer : string
absolute path to the image buffer service
number : int
The number of frames to get. Must be less than the image buffer service's
current buffer size
stalene... | 3.77023 | 3.470445 | 1.086382 |
depth_images = self._ros_read_images(self._depth_image_buffer, num_images, self.staleness_limit)
for i in range(0, num_images):
depth_images[i] = depth_images[i] * MM_TO_METERS # convert to meters
if self._flip_images:
depth_images[i] = np.flipud(depth_im... | def _read_depth_images(self, num_images) | Reads depth images from the device | 2.940789 | 2.902262 | 1.013275 |
color_images = self._ros_read_images(self._color_image_buffer, num_images, self.staleness_limit)
for i in range(0, num_images):
if self._flip_images:
color_images[i] = np.flipud(color_images[i].astype(np.uint8))
color_images[i] = np.fliplr(color_image... | def _read_color_images(self, num_images) | Reads color images from the device | 2.879018 | 2.850736 | 1.009921 |
depths = self._read_depth_images(num_img)
median_depth = Image.median_images(depths)
median_depth.data[median_depth.data == 0.0] = fill_depth
return median_depth | def median_depth_img(self, num_img=1, fill_depth=0.0) | Collect a series of depth images and return the median of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The median DepthImage collected from the frames. | 3.519611 | 4.111837 | 0.85597 |
depths = self._read_depth_images(num_img)
return Image.min_images(depths) | def min_depth_img(self, num_img=1) | Collect a series of depth images and return the min of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The min DepthImage collected from the frames. | 9.260179 | 14.15816 | 0.654052 |
if self.stable_pose is None:
T_obj_world = RigidTransform(from_frame='obj', to_frame='world')
else:
T_obj_world = self.stable_pose.T_obj_table.as_frames('obj', 'world')
T_camera_obj = T_obj_world.inverse() * self.T_camera_world
return T_camera_obj | def T_obj_camera(self) | Returns the transformation from camera to object when the object is in the given stable pose.
Returns
-------
:obj:`autolab_core.RigidTransform`
The desired transform. | 3.423125 | 3.060568 | 1.118461 |
if render_mode == RenderMode.COLOR:
return self.color_im
elif render_mode == RenderMode.DEPTH:
return self.depth_im
elif render_mode == RenderMode.SEGMASK:
return self.binary_im
else:
return None | def image(self, render_mode) | Return an image generated with a particular render mode.
Parameters
----------
render_mode : :obj:`RenderMode`
The type of image we want.
Returns
-------
:obj:`Image`
The color, depth, or binary image if render_mode is
COLOR, DEPTH, o... | 2.556269 | 2.2671 | 1.12755 |
self.features_.append(feature)
self.num_features_ = len(self.features_) | def add(self, feature) | Add a new feature to the bag.
Parameters
----------
feature : :obj:`Feature`
feature to add | 4.100671 | 5.454941 | 0.751735 |
self.features_.extend(features)
self.num_features_ = len(self.features_) | def extend(self, features) | Add a list of features to the bag.
Parameters
----------
feature : :obj:`list` of :obj:`Feature`
features to add | 4.448814 | 5.884033 | 0.756083 |
if index < 0 or index >= self.num_features_:
raise ValueError('Index %d out of range' %(index))
return self.features_[index] | def feature(self, index) | Returns a feature.
Parameters
----------
index : int
index of feature in list
Returns
-------
:obj:`Feature` | 3.647671 | 4.757985 | 0.766642 |
if isinstance(indices, np.ndarray):
indices = indices.tolist()
if not isinstance(indices, list):
raise ValueError('Can only index with lists')
return [self.features_[i] for i in indices] | def feature_subset(self, indices) | Returns some subset of the features.
Parameters
----------
indices : :obj:`list` of :obj:`int`
indices of the features in the list
Returns
-------
:obj:`list` of :obj:`Feature` | 3.477026 | 4.157506 | 0.836325 |
if rospy.get_name() == '/unnamed':
raise ValueError('Weight sensor must be run inside a ros node!')
self._weight_subscriber = rospy.Subscriber('weight_sensor/weights', Float32MultiArray, self._weights_callback)
self._running = True | def start(self) | Start the sensor. | 7.403107 | 6.389857 | 1.158572 |
if not self._running:
return
self._weight_subscriber.unregister()
self._running = False | def stop(self) | Stop the sensor. | 8.694901 | 7.560225 | 1.150085 |
weights = self._raw_weights()
if weights.shape[1] == 0:
return 0.0
elif weights.shape[1] < self._ntaps:
return np.sum(np.mean(weights, axis=1))
else:
return self._filter_coeffs.dot(np.sum(weights, axis=0)) | def total_weight(self) | Read a weight from the sensor in grams.
Returns
-------
weight : float
The sensor weight in grams. | 4.272283 | 4.652349 | 0.918307 |
weights = self._raw_weights()
if weights.shape[1] == 0:
return np.zeros(weights.shape[0])
elif weights.shape[1] < self._ntaps:
return np.mean(weights, axis=1)
else:
return weights.dot(self._filter_coeffs) | def individual_weights(self) | Read individual weights from the load cells in grams.
Returns
-------
weight : float
The sensor weight in grams. | 3.833104 | 4.536433 | 0.84496 |
if self._debug:
return np.array([[],[],[],[]])
if not self._running:
raise ValueError('Weight sensor is not running!')
if len(self._weight_buffers) == 0:
time.sleep(0.3)
if len(self._weight_buffers) == 0:
raise ValueError(... | def _raw_weights(self) | Create a numpy array containing the raw sensor weights. | 3.984508 | 3.398856 | 1.172308 |
# Read weights
weights = np.array(msg.data)
# If needed, initialize indiv_weight_buffers
if len(self._weight_buffers) == 0:
self._weight_buffers = [[] for i in range(len(weights))]
# Record individual weights
for i, w in enumerate(weights):
... | def _weights_callback(self, msg) | Callback for recording weights from sensor. | 3.226987 | 3.206011 | 1.006543 |
return np.r_[self.fx, self.fy, self.cx, self.cy, self.skew, self.height, self.width] | def vec(self) | :obj:`numpy.ndarray` : Vector representation for this camera. | 4.997092 | 3.292459 | 1.517739 |
from sensor_msgs.msg import CameraInfo, RegionOfInterest
from std_msgs.msg import Header
msg_header = Header()
msg_header.frame_id = self._frame
msg_roi = RegionOfInterest()
msg_roi.x_offset = 0
msg_roi.y_offset = 0
msg_roi.height = 0
ms... | def rosmsg(self) | :obj:`sensor_msgs.CamerInfo` : Returns ROS CamerInfo msg | 1.379645 | 1.375922 | 1.002706 |
cx = self.cx + float(width-1)/2 - crop_cj
cy = self.cy + float(height-1)/2 - crop_ci
cropped_intrinsics = CameraIntrinsics(frame=self.frame,
fx=self.fx,
fy=self.fy,
... | def crop(self, height, width, crop_ci, crop_cj) | Convert to new camera intrinsics for crop of image from original camera.
Parameters
----------
height : int
height of crop window
width : int
width of crop window
crop_ci : int
row of crop window center
crop_cj : int
col of... | 2.839606 | 2.665865 | 1.065173 |
center_x = float(self.width-1) / 2
center_y = float(self.height-1) / 2
orig_cx_diff = self.cx - center_x
orig_cy_diff = self.cy - center_y
height = scale * self.height
width = scale * self.width
scaled_center_x = float(width-1) / 2
scaled_center_y... | def resize(self, scale) | Convert to new camera intrinsics with parameters for resized image.
Parameters
----------
scale : float
the amount to rescale the intrinsics
Returns
-------
:obj:`CameraIntrinsics`
camera intrinsics for resized image | 2.136648 | 2.047278 | 1.043653 |
if not isinstance(point_cloud, PointCloud) and not (isinstance(point_cloud, Point) and point_cloud.dim == 3):
raise ValueError('Must provide PointCloud or 3D Point object for projection')
if point_cloud.frame != self._frame:
raise ValueError('Cannot project points in fra... | def project(self, point_cloud, round_px=True) | Projects a point cloud onto the camera image plane.
Parameters
----------
point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point`
A PointCloud or Point to project onto the camera image plane.
round_px : bool
If True, projections are rounded to ... | 2.687979 | 2.37137 | 1.133513 |
point_cloud = self.deproject(depth_image)
point_cloud_im_data = point_cloud.data.T.reshape(depth_image.height, depth_image.width, 3)
return PointCloudImage(data=point_cloud_im_data,
frame=self._frame) | def deproject_to_image(self, depth_image) | Deprojects a DepthImage into a PointCloudImage.
Parameters
----------
depth_image : :obj:`DepthImage`
The 2D depth image to projet into a point cloud.
Returns
-------
:obj:`PointCloudImage`
A point cloud image created from the depth image.
... | 3.556453 | 3.842339 | 0.925596 |
file_root, file_ext = os.path.splitext(filename)
if file_ext.lower() != INTR_EXTENSION:
raise ValueError('Extension %s not supported for CameraIntrinsics. Must be stored with extension %s' %(file_ext, INTR_EXTENSION))
f = open(filename, 'r')
ci = json.load(f)
... | def load(filename) | Load a CameraIntrinsics object from a file.
Parameters
----------
filename : :obj:`str`
The .intr file to load the object from.
Returns
-------
:obj:`CameraIntrinsics`
The CameraIntrinsics object loaded from the file.
Raises
----... | 3.018489 | 2.795688 | 1.079695 |
if 'prestored_data' in cfg.keys() and cfg['prestored_data'] == 1:
sensor = VirtualKinect2Sensor(path_to_images=cfg['prestored_data_dir'], frame=cfg['sensor']['frame'])
else:
sensor = Kinect2Sensor(device_num=cfg['sensor']['device_num'], frame=cfg['sensor']['frame'],
... | def load_images(cfg) | Helper function for loading a set of color images, depth images, and IR
camera intrinsics.
The config dictionary must have these keys:
- prestored_data -- If 1, use the virtual sensor, else use a real sensor.
- prestored_data_dir -- A path to the prestored data dir for a virtual sensor.
... | 3.794122 | 2.286277 | 1.65952 |
if self._device is None:
raise RuntimeError('Kinect2 device %s not runnning. Cannot return color intrinsics')
camera_params = self._device.getColorCameraParams()
return CameraIntrinsics(self._color_frame, camera_params.fx, camera_params.fy,
ca... | def color_intrinsics(self) | :obj:`CameraIntrinsics` : The camera intrinsics for the Kinect's color camera. | 5.081311 | 4.291388 | 1.184072 |
if self._device is None:
raise RuntimeError('Kinect2 device %s not runnning. Cannot return IR intrinsics')
camera_params = self._device.getIrCameraParams()
return CameraIntrinsics(self._ir_frame, camera_params.fx, camera_params.fy,
camera_para... | def ir_intrinsics(self) | :obj:`CameraIntrinsics` : The camera intrinsics for the Kinect's IR camera. | 5.113207 | 4.241294 | 1.205577 |
# open packet pipeline
if self._packet_pipeline_mode == Kinect2PacketPipelineMode.OPENGL:
self._pipeline = lf2.OpenGLPacketPipeline()
elif self._packet_pipeline_mode == Kinect2PacketPipelineMode.CPU:
self._pipeline = lf2.CpuPacketPipeline()
# setup logge... | def start(self) | Starts the Kinect v2 sensor stream.
Raises
------
IOError
If the Kinect v2 is not detected. | 3.303367 | 3.284191 | 1.005839 |
# check that everything is running
if not self._running or self._device is None:
logging.warning('Kinect2 device %d not runnning. Aborting stop' %(self._device_num))
return False
# stop the device
self._device.stop()
self._device.close()
... | def stop(self) | Stops the Kinect2 sensor stream.
Returns
-------
bool
True if the stream was stopped, False if the device was already
stopped or was not otherwise available. | 4.842424 | 4.306726 | 1.124386 |
color_im, depth_im, ir_im, _ = self._frames_and_index_map(skip_registration=skip_registration)
return color_im, depth_im, ir_im | def frames(self, skip_registration=False) | Retrieve a new frame from the Kinect and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`, :obj:`Dept... | 4.674322 | 4.612886 | 1.013318 |
if not self._running:
raise RuntimeError('Kinect2 device %s not runnning. Cannot read frames' %(self._device_num))
# read frames
frames = self._listener.waitForNewFrame()
unregistered_color = frames['color']
distorted_depth = frames['depth']
ir = fra... | def _frames_and_index_map(self, skip_registration=False) | Retrieve a new frame from the Kinect and return a ColorImage,
DepthImage, IrImage, and a map from depth pixels to color pixel indices.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tup... | 2.990165 | 2.7951 | 1.069788 |
encoding = msg.encoding
try:
image = self._bridge.imgmsg_to_cv2(msg, encoding)
except CvBridgeError as e:
rospy.logerr(e)
return image | 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 | 2.624664 | 3.124975 | 0.839899 |
color_arr = self._process_image_msg(image_msg)
self._cur_color_im = ColorImage(color_arr[:,:,::-1], self._frame) | def _color_image_callback(self, image_msg) | subscribe to image topic and keep it up to date | 6.693361 | 6.333189 | 1.056871 |
encoding = image_msg.encoding
try:
depth_arr = self._bridge.imgmsg_to_cv2(image_msg, encoding)
import pdb; pdb.set_trace()
except CvBridgeError as e:
rospy.logerr(e)
depth = np.array(depth_arr*MM_TO_METERS, np.float32)
self._cur_depth... | def _depth_image_callback(self, image_msg) | subscribe to depth image topic and keep it up to date | 3.521926 | 3.51416 | 1.00221 |
# initialize subscribers
self._image_sub = rospy.Subscriber(self.topic_image_color, sensor_msgs.msg.Image, self._color_image_callback)
self._depth_sub = rospy.Subscriber(self.topic_image_depth, sensor_msgs.msg.Image, self._depth_image_callback)
self._camera_info_sub = rospy.Subs... | def start(self) | Start the sensor | 2.203489 | 2.207549 | 0.998161 |
# check that everything is running
if not self._running:
logging.warning('Kinect not running. Aborting stop')
return False
# stop subs
self._image_sub.unregister()
self._depth_sub.unregister()
self._camera_info_sub.unregister
sel... | def stop(self) | Stop the sensor | 5.282899 | 5.026667 | 1.050975 |
# wait for a new image
while self._cur_depth_im is None or self._cur_color_im is None:
time.sleep(0.01)
# read next image
depth_im = self._cur_depth_im
color_im = self._cur_color_im
self._cur_color_im = None
self._cur_depth_im = ... | def frames(self) | Retrieve a new frame from the Ensenso and convert it to a ColorImage,
a DepthImage, IrImage is always none for this type
Returns
-------
:obj:`tuple` of :obj:`ColorImage`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the ... | 3.632915 | 3.307828 | 1.098278 |
if not self._running:
raise RuntimeError('VirtualKinect2 device pointing to %s not runnning. Cannot read frames' %(self._path_to_images))
if self._im_index > self._num_images:
raise RuntimeError('VirtualKinect2 device is out of images')
# read images
co... | def frames(self) | Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`... | 2.526642 | 2.182212 | 1.157835 |
sensor_type = sensor_type.lower()
if sensor_type == 'real':
s = Kinect2Sensor(packet_pipeline_mode=cfg['pipeline_mode'],
device_num=cfg['device_num'],
frame=cfg['frame'])
elif sensor_type == 'virtual':
s... | def sensor(sensor_type, cfg) | Creates a Kinect2 sensor of the specified type.
Parameters
----------
sensor_type : :obj:`str`
the type of the sensor (real or virtual)
cfg : :obj:`YamlConfig`
dictionary of parameters for sensor initialization | 3.806338 | 3.756784 | 1.013191 |
# Get all devices attached as USB serial
all_devices = glob.glob('/dev/ttyUSB*')
# Identify which of the devices are LoadStar Serial Sensors
sensors = []
for device in all_devices:
try:
ser = serial.Serial(port=device,
... | def _connect(self, id_mask) | Connects to all of the load cells serially. | 3.585518 | 3.386987 | 1.058616 |
for ser in self._serials:
ser.flush()
ser.flushInput()
ser.flushOutput()
time.sleep(0.02) | def _flush(self) | Flushes all of the serial ports. | 3.844215 | 3.24912 | 1.183156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.