Put timestamps on Image's name into a bag
I have a folder containing sequence of images with the timestamp which is also the name of each image. I create a bag containing "image topic" , and i want to set header of this topic by these timestamps. But when i run this bag , i think speed of this topic is really fast; It runs just within 2s when normally , the sequence of image(30Hz) runs within 30s.
def getImageFilesFromDir(dir):
'''Generates a list of files from the directory'''
image_files = list()
timestamps = list()
if os.path.exists(dir):
for path, names, files in os.walk(dir):
for f in files:
if os.path.splitext(f)[1] in ['.bmp', '.png', '.jpg']:
image_files.append( os.path.join( path, f ) )
timestamps.append(os.path.splitext(f)[0])
#sort by timestamp
sort_list = sorted(zip(timestamps, image_files))
image_files = [file[1] for file in sort_list]
return image_files
def loadImageToRosMsg(filename):
image_np = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
timestamp_nsecs = os.path.splitext(os.path.basename(filename))[0]
timestamp = rospy.Time( secs=int(timestamp_nsecs[0:-9]), nsecs=int(timestamp_nsecs[-9:]) )
rosimage = Image()
rosimage.header.stamp = timestamp
rosimage.height = image_np.shape[0]
rosimage.width = image_np.shape[1]
rosimage.step = rosimage.width #only with mono8! (step = width * byteperpixel * numChannels)
rosimage.encoding = "mono8"
rosimage.data = image_np.tostring()
return rosimage, timestamp
try:
bag = rosbag.Bag(parsed.output_bag, 'w')
#write images
camfolders = getCamFoldersFromDir(parsed.folder)
for camfolder in camfolders:
camdir = parsed.folder + "/{0}".format(camfolder)
image_files = getImageFilesFromDir(camdir)
for image_filename in image_files:
image_msg, timestamp = loadImageToRosMsg(image_filename)
bag.write("/{0}/image_raw".format(camfolder), image_msg, timestamp)
You could have each iteration sleep the time difference between the last image and the current one, but why would you want it to run slower?
in fact, i put this as the input of SLAM system, the frequency of images reaches normally 30 Hz. What i don't understand is that i put the timestamp of each image in the header of this bag. it means that frequency have to be 30Hz if all things are right.
I misunderstood the question before. Update the question with a list of filenames (
ls -1
in a camera folder) and the timestamps that were put into the bag (rostopic echo /folder/image_raw/header/stamp
while playing the bag) then it could be seen if your code is good.Also the indentation in your quoted code is messed up, making it hard to read.