_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12300 | EnsensoSensor._depth_im_from_pointcloud | train | def _depth_im_from_pointcloud(self, msg):
""" Convert a pointcloud2 message to a depth image. """
# 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._camera_intr.resize(rescale_factor)
# read num points
num_points = msg.height * msg.width
# read buffer | python | {
"resource": ""
} |
q12301 | EnsensoSensor.frames | train | 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.
Raises
------
RuntimeError
If the Ensenso stream is not running.
"""
# wait for a new image
while self._cur_depth_im is None:
| python | {
"resource": ""
} |
q12302 | IterativeRegistrationSolver.register | train | 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.NormalCloud`
source object outward-pointing normals
target_normal_cloud : :obj:`autolab_core.NormalCloud`
target object outward-pointing normals
matcher : :obj:`PointToPlaneFeatureMatcher`
| python | {
"resource": ""
} |
q12303 | TensorDatasetVirtualSensor.frames | train | 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`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the current frame.
Raises
------
RuntimeError
If the stream is not running or if all images in the
directory have been used.
"""
if not self._running:
| python | {
"resource": ""
} |
q12304 | PrimesenseSensor._read_depth_image | train | def _read_depth_image(self):
""" Reads a depth image from the device """
# 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_image = buf_array.reshape(PrimesenseSensor.DEPTH_IM_HEIGHT,
PrimesenseSensor.DEPTH_IM_WIDTH)
| python | {
"resource": ""
} |
q12305 | PrimesenseSensor._read_color_image | train | def _read_color_image(self):
""" Reads a color image from the device """
# 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 range(PrimesenseSensor.COLOR_IM_WIDTH * PrimesenseSensor.COLOR_IM_HEIGHT)])
b_array = np.array([raw_buf[i][2] for i in range(PrimesenseSensor.COLOR_IM_WIDTH * PrimesenseSensor.COLOR_IM_HEIGHT)]) | python | {
"resource": ""
} |
q12306 | PrimesenseSensor_ROS._read_depth_images | train | def _read_depth_images(self, num_images):
""" Reads depth images from the device """
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:
| python | {
"resource": ""
} |
q12307 | PrimesenseSensor_ROS._read_color_images | train | def _read_color_images(self, num_images):
""" Reads color images from the device """
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))
| python | {
"resource": ""
} |
q12308 | ObjectRender.T_obj_camera | train | 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.
"""
if self.stable_pose is None:
T_obj_world = | python | {
"resource": ""
} |
q12309 | QueryImageBundle.image | train | 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`
| python | {
"resource": ""
} |
q12310 | BagOfFeatures.add | train | def add(self, feature):
""" Add a new feature to the bag.
Parameters
----------
feature : :obj:`Feature`
feature to add
"""
| python | {
"resource": ""
} |
q12311 | BagOfFeatures.extend | train | def extend(self, features):
""" Add a list of features to the bag.
Parameters
----------
feature : :obj:`list` of :obj:`Feature`
features to add
"""
| python | {
"resource": ""
} |
q12312 | BagOfFeatures.feature | train | def feature(self, index):
""" Returns a feature.
Parameters
----------
index : int
index of feature in list
Returns
-------
:obj:`Feature`
| python | {
"resource": ""
} |
q12313 | WeightSensor.total_weight | train | def total_weight(self):
"""Read a weight from the sensor in grams.
Returns
-------
weight : float
The sensor weight in grams.
"""
weights = self._raw_weights()
if weights.shape[1] == 0:
return | python | {
"resource": ""
} |
q12314 | WeightSensor.individual_weights | train | def individual_weights(self):
"""Read individual weights from the load cells in grams.
Returns
-------
weight : float
The sensor weight in grams.
"""
weights = self._raw_weights()
if weights.shape[1] == 0:
| python | {
"resource": ""
} |
q12315 | WeightSensor._raw_weights | train | def _raw_weights(self):
"""Create a numpy array containing the raw sensor weights.
"""
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)
| python | {
"resource": ""
} |
q12316 | WeightSensor._weights_callback | train | def _weights_callback(self, msg):
"""Callback for recording weights from sensor.
"""
# 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 | python | {
"resource": ""
} |
q12317 | CameraIntrinsics.crop | train | 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 crop window center
Returns
-------
| python | {
"resource": ""
} |
q12318 | CameraIntrinsics.project | train | 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 the nearest pixel.
Returns
-------
:obj:`autolab_core.ImageCoords` or :obj:`autolab_core.Point`
A corresponding set of image coordinates representing the given
PointCloud's projections onto the camera image plane. If the input
was a single Point, returns a 2D Point in the camera plane.
Raises
------
ValueError
If the input is not a PointCloud or Point in the same reference
frame as the camera.
"""
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 | python | {
"resource": ""
} |
q12319 | CameraIntrinsics.deproject_to_image | train | 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.
Raises
------
ValueError
If depth_image is not a valid DepthImage in the same reference frame
| python | {
"resource": ""
} |
q12320 | load_images | train | 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.
- sensor/frame -- The frame of reference for the sensor.
- sensor/device_num -- The device number for the real Kinect.
- sensor/pipeline_mode -- The mode for the real Kinect's packet pipeline.
- num_images -- The number of images to generate.
Parameters
----------
cfg : :obj:`dict`
A config dictionary.
Returns
-------
:obj:`tuple` of :obj:`list` of :obj:`ColorImage`, :obj:`list` of :obj:`DepthImage`, :obj:`CameraIntrinsics`
A set of ColorImages and DepthImages, and the Kinect's CameraIntrinsics
for its IR sensor.
"""
| python | {
"resource": ""
} |
q12321 | Kinect2Sensor.start | train | def start(self):
"""Starts the Kinect v2 sensor stream.
Raises
------
IOError
If the Kinect v2 is not detected.
"""
# 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 logger
self._logger = lf2.createConsoleLogger(lf2.LoggerLevel.Warning)
lf2.setGlobalLogger(self._logger)
# check devices
self._fn_handle = lf2.Freenect2()
self._num_devices = self._fn_handle.enumerateDevices()
if self._num_devices == 0:
raise IOError('Failed to start stream. No Kinect2 devices available!')
if self._num_devices <= self._device_num:
raise IOError('Failed to start stream. Device num %d unavailable!' %(self._device_num))
# open device
self._serial = self._fn_handle.getDeviceSerialNumber(self._device_num)
| python | {
"resource": ""
} |
q12322 | Kinect2Sensor.stop | train | 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.
"""
# check that everything is running
if not self._running or self._device is None:
| python | {
"resource": ""
} |
q12323 | Kinect2Sensor._frames_and_index_map | train | 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:`tuple` of :obj:`ColorImage`, :obj:`DepthImage`, :obj:`IrImage`, :obj:`numpy.ndarray`
The ColorImage, DepthImage, and IrImage of the current frame, and an
ndarray that maps pixels of the depth image to the index of the
corresponding pixel in the color image.
Raises
------
RuntimeError
If the Kinect stream is not running.
"""
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 = frames['ir']
# apply color to depth registration
color_frame = self._color_frame
color = unregistered_color
depth = distorted_depth
color_depth_map = np.zeros([depth.height, depth.width]).astype(np.int32).ravel()
if not skip_registration and self._registration_mode == Kinect2RegistrationMode.COLOR_TO_DEPTH:
color_frame = self._ir_frame
depth = lf2.Frame(depth.width, depth.height, 4, lf2.FrameType.Depth)
color = lf2.Frame(depth.width, depth.height, 4, lf2.FrameType.Color)
| python | {
"resource": ""
} |
q12324 | KinectSensorBridged._color_image_callback | train | def _color_image_callback(self, image_msg):
""" subscribe to image topic and keep it up to date
"""
| python | {
"resource": ""
} |
q12325 | KinectSensorBridged._depth_image_callback | train | def _depth_image_callback(self, image_msg):
""" subscribe to depth image topic and keep it up to date
"""
encoding = image_msg.encoding
try:
depth_arr = self._bridge.imgmsg_to_cv2(image_msg, encoding)
import pdb; pdb.set_trace()
except CvBridgeError as e:
| python | {
"resource": ""
} |
q12326 | KinectSensorBridged.frames | train | 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 current frame.
Raises
------
RuntimeError
If the Kinect stream is not running.
"""
# wait for a new image | python | {
"resource": ""
} |
q12327 | Kinect2SensorFactory.sensor | train | 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
"""
sensor_type = sensor_type.lower()
if sensor_type == 'real':
s = Kinect2Sensor(packet_pipeline_mode=cfg['pipeline_mode'],
device_num=cfg['device_num'],
| python | {
"resource": ""
} |
q12328 | WeightPublisher._connect | train | def _connect(self, id_mask):
"""Connects to all of the load cells serially.
"""
# 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,
timeout=0.5,
exclusive=True)
ser.write('ID\r')
ser.flush()
time.sleep(0.05)
resp = ser.read(13)
ser.close()
if len(resp) >= 10 and resp[:len(id_mask)] == id_mask:
sensors.append((device, resp.rstrip('\r\n')))
| python | {
"resource": ""
} |
q12329 | WeightPublisher._flush | train | def _flush(self):
"""Flushes all of the serial ports.
"""
for ser in self._serials:
ser.flush()
| python | {
"resource": ""
} |
q12330 | WeightPublisher._read_weights | train | def _read_weights(self):
"""Reads weights from each of the load cells.
"""
weights = []
grams_per_pound = 453.592
# Read from each of the sensors
for ser in self._serials:
ser.write('W\r')
ser.flush()
time.sleep(0.02)
for ser in self._serials:
try:
output_str = ser.readline()
weight = float(output_str) * grams_per_pound
| python | {
"resource": ""
} |
q12331 | _Camera.run | train | def run(self):
""" Continually write images to the filename specified by a command queue. """
if not self.camera.is_running:
self.camera.start()
while True:
if not self.cmd_q.empty():
cmd = self.cmd_q.get()
if cmd[0] == 'stop':
self.out.close()
self.recording = False
elif cmd[0] == 'start':
filename = cmd[1]
self.out = si.FFmpegWriter(filename)
self.recording = True
self.count = 0
if self.recording:
if self.count == 0:
image, _, _ = self.camera.frames()
| python | {
"resource": ""
} |
q12332 | VideoRecorder.start | train | def start(self):
""" Starts the camera recording process. """
self._started = True
self._camera | python | {
"resource": ""
} |
q12333 | VideoRecorder.start_recording | train | def start_recording(self, output_file):
""" Starts recording to a given output video file.
Parameters
----------
output_file : :obj:`str`
filename to write video to
"""
if not self._started:
raise Exception("Must start the video recorder first | python | {
"resource": ""
} |
q12334 | VideoRecorder.stop_recording | train | def stop_recording(self):
""" Stops writing video to file. """
if not self._recording:
raise Exception("Cannot stop a video recording | python | {
"resource": ""
} |
q12335 | VideoRecorder.stop | train | def stop(self):
""" Stop the camera process. """
if not self._started:
raise Exception("Cannot stop a video recorder before starting it!")
self._started = False
if self._actual_camera.is_running:
self._actual_camera.stop()
| python | {
"resource": ""
} |
q12336 | Image._preprocess_data | train | def _preprocess_data(self, data):
"""Converts a data array to the preferred 3D structure.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to process.
Returns
-------
:obj:`numpy.ndarray`
The data re-formatted (if needed) as a 3D matrix
Raises
------
ValueError
If the data is not 1, 2, or 3D to begin with.
"""
original_type = data.dtype
if len(data.shape) == 1:
| python | {
"resource": ""
} |
q12337 | Image.can_convert | train | def can_convert(x):
""" Returns True if x can be converted to an image, False otherwise. """
if len(x.shape) < 2 or len(x.shape) > 3:
return False
dtype = x.dtype
height = x.shape[0]
width = x.shape[1]
| python | {
"resource": ""
} |
q12338 | Image.from_array | train | def from_array(x, frame='unspecified'):
""" Converts an array of data to an Image based on the values in the array and the data format. """
if not Image.can_convert(x):
raise ValueError('Cannot convert array to an Image!')
dtype = x.dtype
height = x.shape[0]
width = x.shape[1]
channels = 1
if len(x.shape) == 3:
channels = x.shape[2]
if dtype == np.uint8:
if channels == 1:
if np.any((x % BINARY_IM_MAX_VAL) > 0):
return GrayscaleImage(x, frame)
return BinaryImage(x, frame)
elif channels == 3:
return ColorImage(x, frame)
else:
raise ValueError(
'No available image conversion for uint8 array with 2 channels')
elif dtype == np.uint16:
if channels != 1:
raise ValueError(
| python | {
"resource": ""
} |
q12339 | Image.align | train | def align(self, scale, center, angle, height, width):
""" Create a thumbnail from the original image that
is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width.
Parameters
----------
scale : float
scale factor to apply
center : 2D array
array containing the row and column index of the pixel to center on | python | {
"resource": ""
} |
q12340 | Image.gradients | train | def gradients(self):
"""Return the gradient as a pair of numpy arrays.
Returns
-------
:obj:`tuple` of :obj:`numpy.ndarray` of float
The gradients | python | {
"resource": ""
} |
q12341 | Image.linear_to_ij | train | def linear_to_ij(self, linear_inds):
"""Converts linear indices to row and column coordinates.
Parameters
----------
linear_inds : :obj:`numpy.ndarray` of int
A list of linear coordinates.
Returns
-------
:obj:`numpy.ndarray` of int
| python | {
"resource": ""
} |
q12342 | Image.median_images | train | def median_images(images):
"""Create a median Image from a list of Images.
Parameters
----------
:obj:`list` of :obj:`Image`
A list of Image objects.
Returns
-------
:obj:`Image`
A new Image of the same type whose data is the median of all of
the images' data.
| python | {
"resource": ""
} |
q12343 | Image.min_images | train | def min_images(images):
"""Create a min Image from a list of Images.
Parameters
----------
:obj:`list` of :obj:`Image`
A list of Image objects.
Returns
-------
:obj:`Image`
A new Image of the same type whose data is the min of all | python | {
"resource": ""
} |
q12344 | Image.apply | train | def apply(self, method, *args, **kwargs):
"""Create a new image by applying a function to this image's data.
Parameters
----------
method : :obj:`function`
A function to call on the data. This takes in a ndarray
as its first argument and optionally takes other arguments.
It should return a modified data ndarray.
args : arguments
Additional args for method.
kwargs : keyword arguments
Additional keyword arguments for method.
| python | {
"resource": ""
} |
q12345 | Image.focus | train | def focus(self, height, width, center_i=None, center_j=None):
"""Zero out all of the image outside of a crop box.
Parameters
----------
height : int
The height of the desired crop box.
width : int
The width of the desired crop box.
center_i : int
The center height point of the crop box. If not specified, the center
of the image is used.
center_j : int
The center width point of the crop box. If not specified, the center
of the image is used.
Returns
-------
:obj:`Image`
A new Image of the same type and size that is zeroed out except
within the crop box.
"""
if center_i is None:
center_i = self.height / 2
if center_j is None:
center_j = self.width / 2
| python | {
"resource": ""
} |
q12346 | Image.center_nonzero | train | def center_nonzero(self):
"""Recenters the image on the mean of the coordinates of nonzero pixels.
Returns
-------
:obj:`Image`
A new Image of the same type and size that is re-centered
at the mean location of the non-zero pixels.
"""
# get the center of the nonzero pixels
nonzero_px = np.where(self._data != 0.0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
mean_px = np.mean(nonzero_px, axis=0)
center_px = (np.array(self.shape) / 2.0)[:2]
diff_px = center_px - mean_px
# transform image
nonzero_px_tf = nonzero_px + diff_px
nonzero_px_tf[:, 0] = np.max(
np.c_[np.zeros(nonzero_px_tf[:, 0].shape), nonzero_px_tf[:, 0]], axis=1)
nonzero_px_tf[:, 0] = np.min(np.c_[(
self.height - 1) * np.ones(nonzero_px_tf[:, 0].shape), nonzero_px_tf[:, 0]], axis=1)
nonzero_px_tf[:, | python | {
"resource": ""
} |
q12347 | Image.nonzero_pixels | train | def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
| python | {
"resource": ""
} |
q12348 | Image.zero_pixels | train | def zero_pixels(self):
""" Return an array of the zero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the zero pixels
"""
| python | {
"resource": ""
} |
q12349 | Image.nan_pixels | train | def nan_pixels(self):
""" Return an array of the NaN pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the NaN pixels
"""
| python | {
"resource": ""
} |
q12350 | Image.finite_pixels | train | def finite_pixels(self):
""" Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels
"""
| python | {
"resource": ""
} |
q12351 | Image.replace_zeros | train | def replace_zeros(self, val, zero_thresh=0.0):
""" Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with
"""
| python | {
"resource": ""
} |
q12352 | Image.save | train | def save(self, filename):
"""Writes the image to a file.
Parameters
----------
filename : :obj:`str`
The file to save the image to. Must be one of .png, .jpg,
.npy, or .npz.
Raises
------
ValueError
If an unsupported file type is specified.
"""
filename = str(filename)
file_root, file_ext = os.path.splitext(filename)
if file_ext in COLOR_IMAGE_EXTS:
im_data = self._image_data()
if im_data.dtype.type == np.uint8:
pil_image = PImage.fromarray(im_data.squeeze())
pil_image.save(filename)
else:
try:
import png
except:
| python | {
"resource": ""
} |
q12353 | Image.savefig | train | def savefig(self, output_path, title, dpi=400, format='png', cmap=None):
"""Write the image to a file using pyplot.
Parameters
----------
output_path : :obj:`str`
The directory in which to place the file.
title : :obj:`str`
The title of the file in which to save the image.
dpi : int
The resolution in dots per inch.
format : :obj:`str`
The file format to save. Available options include .png, .pdf, .ps,
.eps, and .svg.
cmap : :obj:`Colormap`, optional
A Colormap object fo the | python | {
"resource": ""
} |
q12354 | Image.load_data | train | def load_data(filename):
"""Loads a data matrix from a given file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
Returns
-------
:obj:`numpy.ndarray`
The data array read from the file. | python | {
"resource": ""
} |
q12355 | ColorImage._check_valid_data | train | def _check_valid_data(self, data):
"""Checks that the given data is a uint8 array with one or three
channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
if data.dtype.type is not np.uint8:
raise ValueError(
| python | {
"resource": ""
} |
q12356 | ColorImage.swap_channels | train | def swap_channels(self, channel_swap):
""" Swaps the two channels specified in the tuple.
Parameters
----------
channel_swap : :obj:`tuple` of int
the two channels to swap
Returns
-------
:obj:`ColorImage`
color image with cols swapped
"""
if len(channel_swap) != 2:
raise ValueError('Illegal value for channel swap')
ci = channel_swap[0]
cj = channel_swap[1]
if ci < 0 | python | {
"resource": ""
} |
q12357 | ColorImage.find_chessboard | train | def find_chessboard(self, sx=6, sy=9):
"""Finds the corners of an sx X sy chessboard in the image.
Parameters
----------
sx : int
Number of chessboard corners in x-direction.
sy : int
Number of chessboard corners in y-direction.
Returns
-------
:obj:`list` of :obj:`numpy.ndarray`
A list containing the 2D points of the corners of the detected
chessboard, or None if no chessboard found.
"""
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) | python | {
"resource": ""
} |
q12358 | ColorImage.foreground_mask | train | def foreground_mask(
self,
tolerance,
ignore_black=True,
use_hsv=False,
scale=8,
bgmodel=None):
"""Creates a binary image mask for the foreground of an image against
a uniformly colored background. The background is assumed to be the mode value of the histogram
for each of the color channels.
Parameters
----------
tolerance : int
A +/- level from the detected mean backgroud color. Pixels withing
this range will be classified as background pixels and masked out.
ignore_black : bool
If True, the zero pixels will be ignored
when computing the background model.
use_hsv : bool
If True, image will be converted to HSV for background model
generation.
scale : int
Size of background histogram bins -- there will be BINARY_IM_MAX_VAL/size bins
| python | {
"resource": ""
} |
q12359 | ColorImage.background_model | train | def background_model(self, ignore_black=True, use_hsv=False, scale=8):
"""Creates a background model for the given image. The background
color is given by the modes of each channel's histogram.
Parameters
----------
ignore_black : bool
If True, the zero pixels will be ignored
when computing the background model.
use_hsv : bool
If True, image will be converted to HSV for background model
generation.
scale : int
Size of background histogram bins -- there will be BINARY_IM_MAX_VAL/size bins
in the color histogram for each channel.
Returns
-------
A list containing the red, green, and blue channel modes of the
background.
"""
# hsv color
data = self.data
if use_hsv:
pil_im = PImage.fromarray(self._data)
pil_im = pil_im.convert('HSV')
data = np.asarray(pil_im)
# find the black pixels
nonblack_pixels = np.where(np.sum(self.data, axis=2) > 0)
r_data = self.r_data
g_data = self.g_data
b_data = self.b_data
| python | {
"resource": ""
} |
q12360 | ColorImage.draw_box | train | def draw_box(self, box):
"""Draw a white box on the image.
Parameters
----------
:obj:`autolab_core.Box`
A 2D box to draw in the image.
Returns
-------
:obj:`ColorImage`
A new image that is the same as the current one, but with
the white box drawn in.
"""
box_data = self._data.copy()
min_i = box.min_pt[1]
min_j = box.min_pt[0]
max_i = box.max_pt[1]
max_j = box.max_pt[0]
# draw the vertical lines
for j in range(min_j, max_j):
box_data[min_i, | python | {
"resource": ""
} |
q12361 | ColorImage.nonzero_hsv_data | train | def nonzero_hsv_data(self):
""" Computes non zero hsv values.
Returns
-------
:obj:`numpy.ndarray`
array of the hsv values for the image
"""
| python | {
"resource": ""
} |
q12362 | ColorImage.segment_kmeans | train | def segment_kmeans(self, rgb_weight, num_clusters, hue_weight=0.0):
"""
Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
weighting of RGB distance relative to spatial and hue distance
num_clusters : int
number of clusters to use
hue_weight : float
weighting of hue from hsv relative to spatial and RGB distance
Returns
-------
:obj:`SegmentationImage`
image containing the segment labels
"""
# form features array
label_offset = 1
nonzero_px = np.where(self.data != 0.0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
# get hsv data if specified
color_vals = rgb_weight * \
self._data[nonzero_px[:, 0], nonzero_px[:, 1], :]
if hue_weight > 0.0:
hsv_data = cv2.cvtColor(self.data, cv2.COLOR_BGR2HSV)
color_vals = np.c_[color_vals, hue_weight | python | {
"resource": ""
} |
q12363 | ColorImage.to_grayscale | train | def to_grayscale(self):
"""Converts the color image to grayscale using OpenCV.
Returns
-------
:obj:`GrayscaleImage`
Grayscale image corresponding to original color image.
"""
| python | {
"resource": ""
} |
q12364 | ColorImage.open | train | def open(filename, frame='unspecified'):
"""Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
lies.
Returns
| python | {
"resource": ""
} |
q12365 | DepthImage._check_valid_data | train | def _check_valid_data(self, data):
"""Checks that the given data is a float array with one channel.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
if data.dtype.type is not np.float32 and \
data.dtype.type is not np.float64:
raise ValueError(
| python | {
"resource": ""
} |
q12366 | DepthImage.threshold | train | def threshold(self, front_thresh=0.0, rear_thresh=100.0):
"""Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
The upper bound threshold.
Returns
-------
:obj:`DepthImage`
A new DepthImage | python | {
"resource": ""
} |
q12367 | DepthImage.threshold_gradients | train | def threshold_gradients(self, grad_thresh):
"""Creates a new DepthImage by zeroing out all depths
where the magnitude of the gradient at that point is
greater than grad_thresh.
Parameters
----------
grad_thresh : float
A threshold for the gradient magnitude.
Returns
-------
:obj:`DepthImage`
A new DepthImage created from the thresholding operation.
"""
data = np.copy(self._data)
gx, gy = self.gradients()
| python | {
"resource": ""
} |
q12368 | DepthImage.threshold_gradients_pctile | train | def threshold_gradients_pctile(self, thresh_pctile, min_mag=0.0):
"""Creates a new DepthImage by zeroing out all depths
where the magnitude of the gradient at that point is
greater than some percentile of all gradients.
Parameters
----------
thresh_pctile : float
percentile to threshold all gradients above
min_mag : float
minimum magnitude of the gradient
Returns
-------
:obj:`DepthImage`
A new DepthImage created from the thresholding operation.
"""
data = np.copy(self._data)
| python | {
"resource": ""
} |
q12369 | DepthImage.invalid_pixel_mask | train | def invalid_pixel_mask(self):
""" Returns a binary mask for the NaN- and zero-valued pixels.
Serves as a mask for invalid pixels.
Returns
-------
:obj:`BinaryImage`
Binary image where a pixel value greater than zero indicates an invalid pixel.
| python | {
"resource": ""
} |
q12370 | DepthImage.pixels_farther_than | train | def pixels_farther_than(self, depth_im, filter_equal_depth=False):
"""
Returns the pixels that are farther away
than those in the corresponding depth image.
Parameters
----------
depth_im : :obj:`DepthImage`
depth image to query replacement with
filter_equal_depth : bool
whether or not to mark depth values that are equal
Returns
-------
:obj:`numpy.ndarray`
the pixels
""" | python | {
"resource": ""
} |
q12371 | DepthImage.combine_with | train | def combine_with(self, depth_im):
"""
Replaces all zeros in the source depth image with the value of a different depth image
Parameters
----------
depth_im : :obj:`DepthImage`
depth image to combine with
Returns
-------
:obj:`DepthImage`
the combined depth image
"""
new_data = self.data.copy()
# replace zero pixels
new_data[new_data == 0] = depth_im.data[new_data == 0]
| python | {
"resource": ""
} |
q12372 | DepthImage.to_binary | train | def to_binary(self, threshold=0.0):
"""Creates a BinaryImage from the depth image. Points where the depth
is greater than threshold are converted to ones, and all other points
are zeros.
Parameters
----------
threshold : float
The depth threshold.
Returns
-------
:obj:`BinaryImage`
A BinaryImage where all 1 points had | python | {
"resource": ""
} |
q12373 | DepthImage.to_color | train | def to_color(self, normalize=False):
""" Convert to a color image.
Parameters
----------
normalize : bool
whether or not to normalize by the maximum depth
Returns
-------
:obj:`ColorImage`
| python | {
"resource": ""
} |
q12374 | DepthImage.to_float | train | def to_float(self):
""" Converts to 32-bit data.
Returns
-------
:obj:`DepthImage`
depth image with 32 bit float | python | {
"resource": ""
} |
q12375 | DepthImage.point_normal_cloud | train | def point_normal_cloud(self, camera_intr):
"""Computes a PointNormalCloud from the depth image.
Parameters
----------
camera_intr : :obj:`CameraIntrinsics`
The camera parameters on which this depth image was taken.
Returns
-------
:obj:`autolab_core.PointNormalCloud`
A PointNormalCloud created from the depth image.
"""
| python | {
"resource": ""
} |
q12376 | DepthImage.open | train | def open(filename, frame='unspecified'):
"""Creates a DepthImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
lies.
Returns
-------
:obj:`DepthImage`
The new depth image.
| python | {
"resource": ""
} |
q12377 | IrImage.open | train | def open(filename, frame='unspecified'):
"""Creates an IrImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
lies.
Returns
-------
| python | {
"resource": ""
} |
q12378 | GrayscaleImage.to_color | train | def to_color(self):
"""Convert the grayscale image to a ColorImage.
Returns
-------
:obj:`ColorImage`
A color image equivalent to the grayscale one.
"""
| python | {
"resource": ""
} |
q12379 | GrayscaleImage.open | train | def open(filename, frame='unspecified'):
"""Creates a GrayscaleImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
lies.
Returns
| python | {
"resource": ""
} |
q12380 | BinaryImage.pixelwise_or | train | def pixelwise_or(self, binary_im):
""" Takes OR operation with other binary image.
Parameters
----------
binary_im : :obj:`BinaryImage`
binary image for and operation
| python | {
"resource": ""
} |
q12381 | BinaryImage.contour_mask | train | def contour_mask(self, contour):
""" Generates a binary image with only the given contour filled in. """
# fill in new data
new_data = np.zeros(self.data.shape)
num_boundary = contour.boundary_pixels.shape[0]
boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2])
boundary_px_ij_swapped[:, 0, 0] = contour.boundary_pixels[:, 1]
boundary_px_ij_swapped[:, 0, 1] = contour.boundary_pixels[:, 0]
cv2.fillPoly(
new_data, pts=[
boundary_px_ij_swapped.astype(
| python | {
"resource": ""
} |
q12382 | BinaryImage.boundary_map | train | def boundary_map(self):
""" Computes the boundary pixels in the image and sets them to nonzero values.
Returns
-------
:obj:`BinaryImage`
binary image with nonzeros on the boundary of the original image
"""
# compute contours
contours = self.find_contours()
# fill in nonzero pixels
new_data | python | {
"resource": ""
} |
q12383 | BinaryImage.most_free_pixel | train | def most_free_pixel(self):
""" Find the black pixel with the largest distance from the white pixels.
Returns
-------
:obj:`numpy.ndarray`
2-vector containing the most free pixel
"""
dist_tf | python | {
"resource": ""
} |
q12384 | BinaryImage.diff_with_target | train | def diff_with_target(self, binary_im):
""" Creates a color image to visualize the overlap between two images.
Nonzero pixels that match in both images are green.
Nonzero pixels of this image that aren't in the other image are yellow
Nonzero pixels of the other image that aren't in this image are red
Parameters
----------
binary_im : :obj:`BinaryImage`
binary image to take the difference with
Returns
-------
:obj:`ColorImage`
color image to visualize the image difference
"""
red = np.array([BINARY_IM_MAX_VAL, 0, 0])
yellow = np.array([BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL, 0])
green = np.array([0, BINARY_IM_MAX_VAL, 0])
| python | {
"resource": ""
} |
q12385 | BinaryImage.num_adjacent | train | def num_adjacent(self, i, j):
""" Counts the number of adjacent nonzero pixels to a given pixel.
Parameters
----------
i : int
row index of query pixel
j : int
col index of query pixel
Returns
-------
int
number of adjacent nonzero pixels
"""
# check values
if i < 1 or i > self.height - 2 or j < 1 and j > self.width - 2:
| python | {
"resource": ""
} |
q12386 | BinaryImage.to_sdf | train | def to_sdf(self):
""" Converts the 2D image to a 2D signed distance field.
Returns
-------
:obj:`numpy.ndarray`
2D float array of the signed distance field
"""
# compute medial axis transform
skel, sdf_in = morph.medial_axis(self.data, return_distance=True)
useless_skel, sdf_out | python | {
"resource": ""
} |
q12387 | BinaryImage.to_color | train | def to_color(self):
"""Creates a ColorImage from the binary image.
Returns
-------
:obj:`ColorImage`
The newly-created color image.
"""
color_data = np.zeros([self.height, self.width, 3])
color_data[:, :, 0] = self.data
| python | {
"resource": ""
} |
q12388 | BinaryImage.open | train | def open(filename, frame='unspecified'):
"""Creates a BinaryImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
lies.
Returns
-------
:obj:`BinaryImage`
| python | {
"resource": ""
} |
q12389 | RgbdImage._check_valid_data | train | def _check_valid_data(self, data):
"""Checks that the given data is a float array with four channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
if data.dtype.type is not np.float32 and \
data.dtype.type is not np.float64:
raise ValueError(
'Illegal data type. RGB-D images only support float arrays')
if len(data.shape) != 3 and data.shape[2] != 4:
| python | {
"resource": ""
} |
q12390 | RgbdImage.from_color_and_depth | train | def from_color_and_depth(color_im, depth_im):
""" Creates an RGB-D image from a separate color and depth image. """
# check shape
if color_im.height != depth_im.height or color_im.width != depth_im.width:
raise ValueError('Color and depth images must have the same shape')
| python | {
"resource": ""
} |
q12391 | RgbdImage.color | train | def color(self):
""" Returns the color image. """
return | python | {
"resource": ""
} |
q12392 | RgbdImage.combine_with | train | def combine_with(self, rgbd_im):
"""
Replaces all zeros in the source rgbd image with the values of a different rgbd image
Parameters
----------
rgbd_im : :obj:`RgbdImage`
rgbd image to combine with
Returns
-------
:obj:`RgbdImage`
the combined rgbd image
"""
new_data = self.data.copy()
depth_data = self.depth.data
other_depth_data = rgbd_im.depth.data
depth_zero_px = self.depth.zero_pixels()
depth_replace_px = np.where(
(other_depth_data != 0) & (
other_depth_data < depth_data))
depth_replace_px = np.c_[depth_replace_px[0], depth_replace_px[1]]
| python | {
"resource": ""
} |
q12393 | GdImage.from_grayscale_and_depth | train | def from_grayscale_and_depth(gray_im, depth_im):
""" Creates an G-D image from a separate grayscale and depth image. """
# check shape
if gray_im.height != depth_im.height or gray_im.width != depth_im.width:
raise ValueError(
'Grayscale and depth images must have the same shape')
# check frame
if gray_im.frame != depth_im.frame:
raise ValueError(
'Grayscale and depth images must have the same frame')
| python | {
"resource": ""
} |
q12394 | GdImage.gray | train | def gray(self):
""" Returns the grayscale image. """
return GrayscaleImage(
| python | {
"resource": ""
} |
q12395 | SegmentationImage.border_pixels | train | def border_pixels(
self,
grad_sigma=0.5,
grad_lower_thresh=0.1,
grad_upper_thresh=1.0):
"""
Returns the pixels on the boundary between all segments, excluding the zero segment.
Parameters
----------
grad_sigma : float
standard deviation used for gaussian gradient filter
grad_lower_thresh : float
lower threshold on gradient threshold used to determine the boundary pixels
grad_upper_thresh : float
upper threshold on gradient threshold used to determine the boundary pixels
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of pixels on the boundary
"""
# boundary pixels
boundary_im = np.ones(self.shape)
for i in range(1, self.num_segments):
label_border_im = self.data.copy()
label_border_im[self.data == 0] = i
grad_mag = sf.gaussian_gradient_magnitude(
| python | {
"resource": ""
} |
q12396 | SegmentationImage.segment_mask | train | def segment_mask(self, segnum):
""" Returns a binary image of just the segment corresponding to the given number.
Parameters
----------
segnum : int
the number of the segment to generate a | python | {
"resource": ""
} |
q12397 | SegmentationImage.open | train | def open(filename, frame='unspecified'):
""" Opens a segmentation image """
| python | {
"resource": ""
} |
q12398 | PointCloudImage.to_point_cloud | train | def to_point_cloud(self):
"""Convert the image to a PointCloud object.
Returns
-------
:obj:`autolab_core.PointCloud`
The corresponding PointCloud.
"""
return PointCloud(
| python | {
"resource": ""
} |
q12399 | PointCloudImage.normal_cloud_im | train | def normal_cloud_im(self, ksize=3):
"""Generate a NormalCloudImage from the PointCloudImage using Sobel filtering.
Parameters
----------
ksize : int
Size of the kernel to use for derivative computation
Returns
-------
:obj:`NormalCloudImage`
The corresponding NormalCloudImage.
"""
# compute direction via cross product of derivatives
gy = cv2.Sobel(self.data, cv2.CV_64F, 1, 0, ksize=ksize)
gx = cv2.Sobel(self.data, cv2.CV_64F, 0, 1, ksize=ksize)
gx_data = gx.reshape(self.height * self.width, 3)
gy_data = gy.reshape(self.height * self.width, 3)
pc_grads = np.cross(gx_data, gy_data) # default to point toward camera
# normalize
pc_grad_norms = np.linalg.norm(pc_grads, axis=1)
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.