Skip to content

Commit 3b201d6

Browse files
committed
fixing depth image saving #381
1 parent 7a35250 commit 3b201d6

File tree

3 files changed

+114
-65
lines changed

3 files changed

+114
-65
lines changed

atom_calibration/src/atom_calibration/collect/label_messages.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ def labelPointCloud2Msg(msg, seed_x, seed_y, seed_z, threshold, ransac_iteration
4545
pts = points[np.transpose(dist < threshold)[:, 0], :]
4646
idx = np.where(np.transpose(dist < threshold)[:, 0])[0]
4747

48-
4948
# Tracker - update seed point with the average of cluster to use in the next
5049
# iteration
5150
seed_point = []
@@ -59,15 +58,13 @@ def labelPointCloud2Msg(msg, seed_x, seed_y, seed_z, threshold, ransac_iteration
5958
seed_point.append(y_sum / len(pts))
6059
seed_point.append(z_sum / len(pts))
6160

62-
6361
# RANSAC - eliminate the tracker outliers
6462
number_points = pts.shape[0]
6563
if number_points < 10:
6664
labels = {'detected': False, 'idxs': [], 'idxs_limit_points': [], 'idxs_middle_points': []}
6765
seed_point = [seed_x, seed_y, seed_z]
6866
return labels, seed_point, []
6967

70-
7168
# RANSAC iterations
7269
for i in range(0, ransac_iterations):
7370

@@ -126,7 +123,6 @@ def labelPointCloud2Msg(msg, seed_x, seed_y, seed_z, threshold, ransac_iteration
126123
if idx_map[key] < ransac_threshold:
127124
final_idx.append(key)
128125

129-
130126
# -------------------------------------- End of RANSAC ----------------------------------------- #
131127

132128
# Update the dictionary with the labels (to be saved if the user selects the option)
@@ -233,6 +229,10 @@ def convertDepthImage32FC1to16UC1(image_in, scale=1000.0):
233229
:return: np array with dtype uint16
234230
"""
235231

232+
if image_in.dtype == np.uint16:
233+
raise ValueError("Cannot convert float32 to uint16 because image is already uint16.")
234+
# return image_in
235+
236236
# mask_nans = np.isnan(image_in)
237237
image_mm_float = image_in * scale # convert meters to millimeters
238238
image_mm_float = np.round(image_mm_float) # round the millimeters
@@ -565,8 +565,8 @@ def labelDepthMsg(msg, seed, propagation_threshold=0.2, bridge=None, pyrdown=0,
565565

566566
# TODO Why not test if the original image is nan?
567567
if not np.isnan(image[y, x]):
568-
if x < (width-1-(width-1)*filter_border_edges) and x >(width-1)*filter_border_edges:
569-
if y < (height-1-(height-1)*filter_border_edges) and y >(height-1)*filter_border_edges:
568+
if x < (width - 1 - (width - 1) * filter_border_edges) and x > (width - 1) * filter_border_edges:
569+
if y < (height - 1 - (height - 1) * filter_border_edges) and y > (height - 1) * filter_border_edges:
570570
idxs_rows.append(y)
571571
idxs_cols.append(x)
572572

@@ -577,7 +577,7 @@ def labelDepthMsg(msg, seed, propagation_threshold=0.2, bridge=None, pyrdown=0,
577577
idxs_rows = idxs_rows * (2 * pyrdown) # compensate the pyr down
578578
idxs_cols = idxs_cols * (2 * pyrdown)
579579

580-
#check if point is in the image's limits
580+
# check if point is in the image's limits
581581
idxs = idxs_cols + original_width * idxs_rows # we will store the linear indices
582582
idxs = idxs.tolist()
583583
idxs = idxs[::limit_sample_step] # subsample the limit points

atom_calibration/src/atom_calibration/dataset_playback/visualization.py

+102-54
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import math
88
import os
99

10-
1110
import struct
1211

1312
# 3rd-party
@@ -60,6 +59,7 @@ def getPointsInSensorAsNPArray_local(_collection_key, _sensor_key, _label_key, _
6059
points[3, :] = 1
6160
return points
6261

62+
6363
def getCvImageFromCollectionSensor(collection_key, sensor_key, dataset):
6464
dictionary = dataset['collections'][collection_key]['data'][sensor_key]
6565
return getCvImageFromDictionary(dictionary)
@@ -212,7 +212,7 @@ def setupVisualization(dataset, args, selected_collection_key):
212212
# Create image publishers ----------------------------------------------------------
213213
# We need to republish a new image at every visualization
214214
for sensor_key, sensor in dataset['sensors'].items():
215-
if sensor['modality'] == 'rgb':
215+
if sensor['modality'] == 'rgb':
216216
msg_type = sensor_msgs.msg.Image
217217
topic = dataset['calibration_config']['sensors'][sensor_key]['topic_name']
218218
topic_name = topic + '/labeled'
@@ -224,30 +224,38 @@ def setupVisualization(dataset, args, selected_collection_key):
224224
graphics['collections'][str(sensor_key)]['publisher_camera_info'] = \
225225
rospy.Publisher(topic_name, msg_type, queue_size=0, latch=True)
226226

227+
if sensor['modality'] == 'depth':
228+
msg_type = sensor_msgs.msg.Image
229+
topic = dataset['calibration_config']['sensors'][sensor_key]['topic_name']
230+
topic_name = topic + '/labeled'
231+
graphics['collections'][str(sensor_key)] = {'publisher': rospy.Publisher(
232+
topic_name, msg_type, queue_size=0, latch=True)}
233+
print('Created image publisher')
234+
msg_type = sensor_msgs.msg.CameraInfo
235+
topic_name = str(sensor_key) + '/camera_info'
236+
graphics['collections'][str(sensor_key)]['publisher_camera_info'] = \
237+
rospy.Publisher(topic_name, msg_type, queue_size=0, latch=True)
227238
# Create Labeled and Unlabeled Data publishers ----------------------------------------------------------
228239
markers = MarkerArray()
229-
240+
230241
lidar_data = []
231242
graphics['ros']['PubPointCloud'] = dict()
232243
for sensor_key, sensor in dataset['sensors'].items():
233244
if sensor['modality'] == 'lidar3d':
234245
graphics['ros']['PubPointCloud'][sensor_key] = \
235246
rospy.Publisher(str(sensor_key) + '/points', PointCloud2, queue_size=0, latch=True)
236-
247+
237248
for collection_key, collection in dataset['collections'].items():
238249
# if not collection['labels'][str(sensor_key)]['detected']: # not detected by sensor in collection
239250
# continue
240-
251+
241252
# when the sensor has no label, the 'idxs_limit_points' does not exist!!!
242253
if 'idxs_limit_points' not in collection['labels'][str(sensor_key)]:
243254
collection['labels'][str(sensor_key)]['idxs_limit_points'] = []
244-
255+
245256
if collection['labels'][str(sensor_key)]['idxs'] != []:
246257
collection['labels'][str(sensor_key)]['detected'] = True
247-
248-
249-
250-
258+
251259
# if sensor['msg_type'] == 'LaserScan': # -------- Publish the laser scan data ------------------------------
252260
if sensor['modality'] == 'lidar2d':
253261
frame_id = genCollectionPrefix(collection_key, collection['data'][sensor_key]['header']['frame_id'])
@@ -304,7 +312,7 @@ def setupVisualization(dataset, args, selected_collection_key):
304312

305313
# if sensor['msg_type'] == 'PointCloud2': # -------- Publish the velodyne data ------------------------------
306314
if sensor['modality'] == 'lidar3d':
307-
315+
308316
# Add labelled points to the marker
309317
frame_id = genCollectionPrefix(collection_key, collection['data'][sensor_key]['header']['frame_id'])
310318
marker = Marker(header=Header(frame_id=frame_id, stamp=now),
@@ -344,17 +352,18 @@ def setupVisualization(dataset, args, selected_collection_key):
344352
markers.markers.append(copy.deepcopy(marker))
345353

346354
# Add 3D lidar data
347-
original_pointcloud_msg = getPointCloudMessageFromDictionary(dataset['collections'][collection_key]['data'][sensor_key])
355+
original_pointcloud_msg = getPointCloudMessageFromDictionary(
356+
dataset['collections'][collection_key]['data'][sensor_key])
348357
final_pointcloud_msg = PointCloud2(header=Header(frame_id=frame_id, stamp=now),
349-
height=original_pointcloud_msg.height, width=original_pointcloud_msg.width,
350-
fields=original_pointcloud_msg.fields, is_bigendian=original_pointcloud_msg.is_bigendian,
351-
point_step=original_pointcloud_msg.point_step, row_step=original_pointcloud_msg.row_step,
352-
data=original_pointcloud_msg.data, is_dense=original_pointcloud_msg.is_dense)
358+
height=original_pointcloud_msg.height,
359+
width=original_pointcloud_msg.width,
360+
fields=original_pointcloud_msg.fields,
361+
is_bigendian=original_pointcloud_msg.is_bigendian,
362+
point_step=original_pointcloud_msg.point_step,
363+
row_step=original_pointcloud_msg.row_step,
364+
data=original_pointcloud_msg.data,
365+
is_dense=original_pointcloud_msg.is_dense)
353366
lidar_data.append(final_pointcloud_msg)
354-
355-
356-
357-
358367

359368
graphics['ros']['MarkersLabeled'] = markers
360369
graphics['ros']['PointClouds'] = lidar_data
@@ -542,7 +551,7 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
542551
graphics = models['graphics']
543552

544553
collection = dataset['collections'][selected_collection_key]
545-
554+
546555
# print("args['initial_pose_ghost'])" + str(args['initial_pose_ghost']))
547556

548557
now = rospy.Time.now() # time used to publish all visualization messages
@@ -640,55 +649,54 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
640649
# Update timestamp for pointcloud2 message
641650
for pointcloud_msg in graphics['ros']['PointClouds']:
642651
pointcloud_msg.header.stamp = now
643-
644-
#print(graphics['ros']['PointClouds'])
652+
653+
# print(graphics['ros']['PointClouds'])
645654
# Create a new pointcloud which contains only the points related to the selected collection
646655
for pointcloud_msg in graphics['ros']['PointClouds']:
647-
656+
648657
prefix = pointcloud_msg.header.frame_id.split('_')[0] + '_'
649658
sensor = pointcloud_msg.header.frame_id[len(prefix):]
650-
659+
651660
# prof. Miguel these two lines that you wrote wasted 2 hours of my life!
652-
#prefix = pointcloud_msg.header.frame_id[:3]
653-
#sensor = pointcloud_msg.header.frame_id[3:]
654-
655-
#print('-----------------------------------------------------------')
661+
# prefix = pointcloud_msg.header.frame_id[:3]
662+
# sensor = pointcloud_msg.header.frame_id[3:]
663+
664+
# print('-----------------------------------------------------------')
656665
if prefix == 'c' + str(selected_collection_key) + '_':
657666
# change intensity channel according to the idxs
658667
points_collection = pc2.read_points(pointcloud_msg)
659668
gen_points = list(points_collection)
660669
final_points = []
661-
670+
662671
idxs = dataset['collections'][selected_collection_key]['labels'][sensor]['idxs']
663672
idxs_limit_points = dataset['collections'][selected_collection_key]['labels'][sensor]['idxs_limit_points']
664673
sensor_idx = list(dataset['collections'][selected_collection_key]['labels'].keys()).index(sensor)
665-
674+
666675
for idx, point in enumerate(gen_points):
667676
if idx in idxs_limit_points:
668-
r,g,b = 50,70,20
677+
r, g, b = 50, 70, 20
669678
elif idx in idxs:
670-
r,g,b = 100,220,20
679+
r, g, b = 100, 220, 20
671680
else:
672-
r,g,b = 186,189, 182
673-
681+
r, g, b = 186, 189, 182
682+
674683
point_color = [point[0], point[1], point[2], idx, 0, sensor_idx]
675684
rgb = struct.unpack('I', struct.pack('BBBB', b, g, r, 255))[0]
676685
point_color[4] = rgb
677-
686+
678687
final_points.append(point_color)
679-
688+
680689
fields = [PointField('x', 0, PointField.FLOAT32, 1),
681-
PointField('y', 4, PointField.FLOAT32, 1),
682-
PointField('z', 8, PointField.FLOAT32, 1),
683-
PointField('idx', 12, PointField.FLOAT32, 1),
684-
PointField('rgb', 20, PointField.UINT32, 1),
685-
PointField('sensor_idx', 24, PointField.FLOAT32, 1)
686-
]
690+
PointField('y', 4, PointField.FLOAT32, 1),
691+
PointField('z', 8, PointField.FLOAT32, 1),
692+
PointField('idx', 12, PointField.FLOAT32, 1),
693+
PointField('rgb', 20, PointField.UINT32, 1),
694+
PointField('sensor_idx', 24, PointField.FLOAT32, 1)
695+
]
687696
pointcloud_msg_final = pc2.create_cloud(pointcloud_msg.header, fields, final_points)
688-
697+
689698
# create a new point cloud2, and change a value related to the idx
690699
graphics['ros']['PubPointCloud'][sensor].publish(pointcloud_msg_final)
691-
692700

693701
# Create a new marker array which contains only the marker related to the selected collection
694702
# Publish the pattern data
@@ -698,7 +706,8 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
698706
if prefix == 'c' + str(selected_collection_key) + '_':
699707
marker_array_1.markers.append(marker)
700708
marker_array_1.markers[-1].action = Marker.ADD
701-
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(previous_selected_collection_key) + '_':
709+
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(
710+
previous_selected_collection_key) + '_':
702711
marker_array_1.markers.append(marker)
703712
marker_array_1.markers[-1].action = Marker.DELETE
704713
graphics['ros']['PubPattern'].publish(marker_array_1)
@@ -711,7 +720,8 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
711720
if prefix == 'c' + str(selected_collection_key) + '_':
712721
marker_array_2.markers.append(marker)
713722
marker_array_2.markers[-1].action = Marker.ADD
714-
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(previous_selected_collection_key) + '_':
723+
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(
724+
previous_selected_collection_key) + '_':
715725
marker_array_2.markers.append(marker)
716726
marker_array_2.markers[-1].action = Marker.DELETE
717727
graphics['ros']['publisher_models'].publish(graphics['ros']['robot_mesh_markers'])
@@ -724,7 +734,8 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
724734
if prefix == 'c' + str(selected_collection_key) + '_':
725735
marker_array_3.markers.append(marker)
726736
marker_array_3.markers[-1].action = Marker.ADD
727-
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(previous_selected_collection_key) + '_':
737+
elif not previous_selected_collection_key == selected_collection_key and prefix == 'c' + str(
738+
previous_selected_collection_key) + '_':
728739
marker_array_3.markers.append(marker)
729740
marker_array_3.markers[-1].action = Marker.DELETE
730741

@@ -775,15 +786,52 @@ def visualizationFunction(models, selected_collection_key, previous_selected_col
775786
graphics['collections'][sensor_key]['publisher_camera_info'].publish(
776787
camera_info_msg)
777788

789+
if sensor['modality'] == 'depth':
790+
if args['show_images']:
791+
collection = collections[selected_collection_key]
792+
image = copy.deepcopy(getCvImageFromCollectionSensor(selected_collection_key, sensor_key, dataset))
793+
width = collection['data'][sensor_key]['width']
794+
height = collection['data'][sensor_key]['height']
795+
idxs = dataset['collections'][selected_collection_key]['labels'][sensor_key]['idxs']
796+
idxs_limit_points = dataset['collections'][selected_collection_key]['labels'][sensor_key][
797+
'idxs_limit_points']
798+
gui_image = np.zeros((height, width, 3), dtype=np.uint8)
799+
max_value = 5
800+
gui_image[:, :, 0] = image / max_value * 255
801+
gui_image[:, :, 1] = image / max_value * 255
802+
gui_image[:, :, 2] = image / max_value * 255
803+
804+
for idx in idxs:
805+
# convert from linear idx to x_pix and y_pix indices.
806+
y = int(idx / width)
807+
x = int(idx - y * width)
808+
cv2.line(gui_image, (x, y), (x, y), (0, 200, 255), 3)
809+
810+
for idx in idxs_limit_points:
811+
# convert from linear idx to x_pix and y_pix indices.
812+
y = int(idx / width)
813+
x = int(idx - y * width)
814+
cv2.line(gui_image, (x, y), (x, y), (255, 0, 200), 3)
815+
816+
msg = CvBridge().cv2_to_imgmsg(gui_image, "passthrough")
817+
818+
msg.header.frame_id = 'c' + selected_collection_key + '_' + sensor['parent']
819+
graphics['collections'][sensor_key]['publisher'].publish(msg)
778820

821+
# Publish camera info message
822+
camera_info_msg = message_converter.convert_dictionary_to_ros_message('sensor_msgs/CameraInfo',
823+
sensor['camera_info'])
824+
camera_info_msg.header.frame_id = msg.header.frame_id
825+
graphics['collections'][sensor_key]['publisher_camera_info'].publish(
826+
camera_info_msg)
779827

780828
# elif sensor['msg_type'] == 'LaserScan':
781-
elif sensor['modality'] == 'lidar2d':
782-
pass
829+
elif sensor['modality'] == 'lidar2d':
830+
pass
783831
# elif sensor['msg_type'] == 'PointCloud2':
784-
elif sensor['modality'] == 'lidar3d':
785-
pass
786-
else:
787-
pass
832+
elif sensor['modality'] == 'lidar3d':
833+
pass
834+
else:
835+
pass
788836

789837
graphics['ros']['Rate'].sleep()

atom_core/src/atom_core/dataset_io.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -228,12 +228,11 @@ def createDataFile(dataset, collection_key, sensor, sensor_key, output_folder, d
228228
# filename_np=output_folder + '/' + sensor['_name'] + '_' + str(collection_key) + '.npy'
229229
if not os.path.isfile(filename): # Write pointcloud to pcd file
230230
cv_image = getCvImageFromDictionaryDepth(dataset['collections'][collection_key][data_type][sensor_key])
231-
print("image from getimage")
232-
print(cv_image.dtype)
231+
# print("image from getimage")
232+
# print(cv_image.dtype)
233233
cv_image = convertDepthImage32FC1to16UC1(cv_image, scale=10000) # Better to use tenths of milimeters
234234
# cv2.normalize(cv_image, cv_image, 0, 65535, cv2.NORM_MINMAX)
235-
# cv2.imwrite(filename, cv_image)
236-
imageio.imwrite(filename, cv_image)
235+
cv2.imwrite(filename, cv_image)
237236
print('Saved file ' + filename + '.')
238237

239238
# Add data_file field, and remove data field
@@ -304,6 +303,8 @@ def getCvImageFromDictionaryDepth(dictionary_in, safe=False):
304303
msg = message_converter.convert_dictionary_to_ros_message('sensor_msgs/Image', d)
305304
bridge = CvBridge()
306305
image = bridge.imgmsg_to_cv2(msg, desired_encoding='passthrough')
306+
if image.dtype==np.uint16:
307+
image=convertDepthImage16UC1to32FC1(image)
307308
# print("image inside get image: ")
308309
# print(image.dtype)
309310
return image

0 commit comments

Comments
 (0)