log_images.py
Go to the documentation of this file.
00001 #!/usr/bin/python
00002 
00003 import sys, os
00004 sys.path.append(os.environ['HRLBASEPATH']+'/src/libraries/')
00005 import cameras.dragonfly as dr
00006 import roslib; roslib.load_manifest('modeling_forces')
00007 import rospy
00008 import cv
00009 
00010 from collections import deque
00011 import time
00012 import math, numpy as np
00013 import glob
00014 
00015 import hrl_lib.util as ut
00016 import hrl_camera.ros_camera as rc
00017 
00018 def got_pose_cb(data, got_pose_dict):
00019     if len(data.objects) != 2:
00020         got_pose_dict['pose_fail'] = True
00021     else:
00022         got_pose_dict['pose_fail'] = False
00023 
00024     got_pose_dict['flag'] = True
00025 
00026 
00027 if __name__ == '__main__':
00028     import optparse
00029     p = optparse.OptionParser()
00030     p.add_option('-l', '--log', action='store_true', dest='log', help='log FT data')
00031     p.add_option('-p', '--pub', action='store_true', dest='pub',
00032                  help='publish over ROS')
00033     p.add_option('-c', '--conv', action='store_true', dest='avi_to_pngs',
00034                  help='convert avi to pngs')
00035     p.add_option('-b', '--bad', action='store_true', dest='bad',
00036                  help='find the images on which checker tracking failed.')
00037     p.add_option('-d', '--dir', action='store', default='',
00038                  type='string', dest='dir', help='directory with images')
00039     p.add_option('-i', '--images_only', action='store_true',
00040                  dest='images_only', help='work with images (no pkl)')
00041     p.add_option('-s', '--single_im', action='store', default='',
00042                  type='string', dest='single_fname', help='work with one image')
00043     
00044     opt, args = p.parse_args()
00045 
00046     camera_name = 'remote_head'
00047 
00048     if opt.pub:
00049         import cv
00050         from cv_bridge.cv_bridge import CvBridge, CvBridgeError
00051         from std_msgs.msg import String
00052         from std_msgs.msg import Empty
00053         from sensor_msgs.msg import Image
00054         from sensor_msgs.msg import CameraInfo
00055         from checkerboard_detector.msg import ObjectDetection
00056 
00057         rospy.init_node('publish_log_images', anonymous=True)
00058 
00059         if opt.single_fname != '':
00060             im_name_list = [opt.single_fname for i in range(10)]
00061             time_list = [time.time() for i in range(10)]
00062         elif opt.images_only:
00063             im_name_list = glob.glob(opt.dir+'/*.png')
00064             #im_name_list = glob.glob(opt.dir+'/*.jpg')
00065             im_name_list.sort()
00066             time_list = [1 for i in range(len(im_name_list))]
00067         else:
00068             l = glob.glob(opt.dir+'/handheld_pull_log*.pkl')
00069             if l == []:
00070                 raise RuntimeError('%s does not have a handheld_pull_log'%opt.dir)
00071 
00072             pkl_name = l[0]
00073             d = ut.load_pickle(pkl_name)
00074             im_name_list = glob.glob(opt.dir+'/0*.png')
00075             im_name_list.sort()
00076             time_list = d['time_list']
00077 
00078 
00079         import camera_config as cc
00080         cp = cc.camera_parameters[camera_name]
00081         m = np.array([ [ cp['focal_length_x_in_pixels'], 0.,
00082                          cp['optical_center_x_in_pixels'], 0. ],
00083                        [ 0., cp['focal_length_y_in_pixels'],
00084                          cp['optical_center_y_in_pixels'], 0. ],
00085                        [ 0., 0., 1., 0.] ])
00086 
00087         intrinsic_list = [m[0,0], m[0,1], m[0,2], 0.0,
00088                           m[1,0], m[1,1], m[1,2], 0.0,
00089                           m[2,0], m[2,1], m[2,2], 0.0]
00090 
00091         topic_name = 'cvcamera_' + camera_name
00092         image_pub = rospy.Publisher(topic_name, Image)
00093         config_pub = rospy.Publisher(topic_name+'_info', CameraInfo)
00094         ch_pub = rospy.Publisher('/checker_to_poses/trigger', Empty)
00095 
00096         time.sleep(0.5)
00097         bridge = CvBridge()
00098 
00099         got_pose_dict = {'flag': False, 'pose_fail': False}
00100         topic_name_cb = '/checkerdetector/ObjectDetection'
00101         rospy.Subscriber(topic_name_cb, ObjectDetection, got_pose_cb,
00102                          got_pose_dict)
00103 
00104         failed_im_list = [] # list of filenames on which checkboard detection failed.
00105         n_images = len(im_name_list)
00106         for i in range(n_images):
00107             name = im_name_list[i]
00108             cv_im = cv.LoadImage(name)
00109 
00110             rosimage = bridge.cv_to_imgmsg(cv_im, "bgr8")
00111             rosimage.header.stamp = rospy.Time.from_sec(time_list[i])
00112 
00113             image_pub.publish(rosimage)
00114             config_pub.publish(CameraInfo(P=intrinsic_list))
00115 
00116             t_st = time.time()
00117             while got_pose_dict['flag'] == False:
00118                 time.sleep(0.5)
00119                 if (time.time()-t_st) > 10.:
00120                     break
00121 
00122             if got_pose_dict['pose_fail'] == True:
00123                 failed_im_list.append(name)
00124 
00125             time.sleep(0.5)
00126             got_pose_dict['flag'] = False
00127             got_pose_dict['pose_fail'] = False
00128 
00129             if rospy.is_shutdown():
00130                 break
00131 
00132         print 'Number of images:', n_images
00133         ch_pub.publish() # send trigger to the ft logger.
00134         ut.save_pickle(failed_im_list, 'checker_fail_list.pkl')
00135 
00136     if opt.log:
00137         from opencv.cv import *
00138         from opencv.highgui import *
00139 
00140         from std_msgs.msg import Empty
00141         rospy.init_node('image logger', anonymous=True)
00142         ft_pub = rospy.Publisher('/ftlogger/trigger', Empty)
00143 
00144 
00145         cam = dr.dragonfly2(camera_name)
00146         cam.set_frame_rate(30)
00147         cam.set_brightness(0, 651, 0, 65)
00148         for i in range(10):
00149             im = cam.get_frame_debayered() # undistorting slows down frame rate
00150 
00151         im_list = deque()
00152         time_list = []
00153 
00154         cvNamedWindow('Image Logging', CV_WINDOW_AUTOSIZE)
00155 
00156         print 'Started the loop.'
00157         print 'Hit a to start logging, ESC to exit and save pkl'
00158         log_images = False
00159 
00160         while not rospy.is_shutdown():
00161             kp = cvWaitKey(1)
00162             if (type(kp) == str and kp == '\x1b') or (type(kp) != str and kp & 255 == 27): # ESC then exit.
00163                 t1 = time.time()
00164                 ft_pub.publish() # send trigger to the ft logger.
00165                 break
00166             if (type(kp) == str and kp == 'a') or (type(kp) != str and kp & 255 == 97): # a to start logging.
00167                 log_images = True
00168                 t0 = time.time()
00169                 ft_pub.publish() # send trigger to the ft logger.
00170                 print 'started logging'
00171 
00172             im = cam.get_frame_debayered() # undistorting slows down frame rate
00173             if log_images:
00174                 time_list.append(time.time())
00175                 im_list.append(cvCloneImage(im))
00176         
00177         print 'frame rate:', len(time_list)/(t1-t0)
00178         
00179         print 'before saving the pkl'
00180         d = {}
00181 
00182         t_string = ut.formatted_time()
00183         video_name = 'mechanism_video_'+t_string+'.avi'
00184         vwr = cvCreateVideoWriter(video_name, CV_FOURCC('I','4','2','0'),
00185                                   30, cvGetSize(im_list[0]), True)
00186 
00187         t0 = time.time()
00188         im_name_list = []
00189         time_stamp = ut.formatted_time()
00190         for im in im_list:
00191             cvWriteFrame(vwr, im)
00192             time.sleep(.01) #Important to keep force torque server
00193                             #from restarting
00194         t1 = time.time()
00195         print 'disk writing rate:', len(time_list)/(t1-t0)
00196 
00197         d['time_list'] = time_list
00198         d['video_name'] = video_name
00199 
00200         fname = 'handheld_pull_log_' + t_string + '.pkl'
00201         ut.save_pickle(d, fname)
00202 
00203         print 'Done saving the pkl'
00204 
00205     if opt.avi_to_pngs:
00206         from opencv.cv import *
00207         from opencv.highgui import *
00208         import util
00209 
00210         import camera_config as cc
00211         cp = cc.camera_parameters[camera_name]
00212 
00213         size = (int(cp['calibration_image_width']), int(cp['calibration_image_height']))
00214         color = cp['color']
00215         intrinsic_cvmat = cvCreateMat(3,3,cv.CV_32FC1)
00216         distortion_cvmat = cvCreateMat(1,4,cv.CV_32FC1)
00217 
00218         imat_np = np.array([[cp['focal_length_x_in_pixels'],0,
00219                              cp['optical_center_x_in_pixels']],
00220                             [0,cp['focal_length_y_in_pixels'],
00221                              cp['optical_center_y_in_pixels']],
00222                             [0,0,1]])
00223         intrinsic_cvmat = util.numpymat2cvmat(imat_np)
00224 
00225         dmat_np = np.array([[cp['lens_distortion_radial_1'],
00226                              cp['lens_distortion_radial_2'],
00227                              cp['lens_distortion_tangential_1'],
00228                              cp['lens_distortion_tangential_2']]])
00229 
00230         distortion_cvmat = util.numpymat2cvmat(dmat_np)
00231         undistort_mapx = cvCreateImage(size, IPL_DEPTH_32F, 1)
00232         undistort_mapy = cvCreateImage(size, IPL_DEPTH_32F, 1)
00233         cvInitUndistortMap(intrinsic_cvmat, distortion_cvmat,
00234                            undistort_mapx, undistort_mapy)
00235 
00236         if color == True:
00237             undistort_image = cvCreateImage(size, IPL_DEPTH_8U, 3)
00238         else:
00239             undistort_image = cvCreateImage(size, IPL_DEPTH_8U, 1)
00240 
00241         #pkl_name = glob.glob(opt.dir+'/handheld_pull_log*.pkl')[0]
00242         #d = ut.load_pickle(pkl_name)
00243         #video_name = opt.dir+'/'+d['video_name']
00244         #time_list = d['time_list']
00245 
00246         video_name = glob.glob(opt.dir + 'mechanism_video*.avi')[0]
00247         cap = cvCreateFileCapture(video_name)
00248 
00249         #for i in range(len(time_list)):
00250         i = 0
00251         while True:
00252             cvim = cvQueryFrame(cap)
00253             if cvim == None:
00254                 break
00255             cvFlip(cvim, cvim)
00256             # undistort the image
00257             cvRemap(cvim, undistort_image, undistort_mapx, undistort_mapy,
00258                     CV_INTER_LINEAR, cvScalarAll(0)) 
00259             nm = opt.dir+'/%05d.png'%i
00260             print 'Saving', nm
00261             cvSaveImage(nm, undistort_image)
00262             i += 1
00263 
00264     if opt.bad:
00265         import cv
00266 
00267         l = ut.load_pickle(opt.dir+'/checker_fail_list.pkl')
00268         display = False
00269 
00270         if display:
00271             wnd = 'Checker Fail Images'
00272             cv.NamedWindow(wnd, cv.CV_WINDOW_AUTOSIZE)
00273         else:
00274             save_dir = opt.dir+'/checker_fail/'
00275             os.system('mkdir %s'%save_dir)
00276         for nm in l:
00277             name = opt.dir+'/'+nm
00278             cv_im = cv.LoadImage(name)
00279             if display:
00280                 cv.ShowImage(wnd, cv_im)
00281                 cv.WaitKey(0)
00282             else:
00283                 save_dir = os.path.normpath(save_dir)
00284 #                print 'save_dir:', save_dir
00285                 file_name = '_'.join(save_dir.split('/')) + '_%s'%os.path.normpath(nm)
00286                 print 'file_name:', file_name
00287                 cv.SaveImage(save_dir + '/' + file_name, cv_im)
00288 
00289 
00290 
00291 


2010_biorob_everyday_mechanics
Author(s): Advait Jain, Hai Nguyen, Charles C. Kemp (Healthcare Robotics Lab, Georgia Tech)
autogenerated on Wed Nov 27 2013 11:58:43