pascal_preprocess.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from skimage import io, transform
  2. from multiprocessing.dummy import Pool as ThreadPool
  3. def rescale(root_new, root_old, img_path, ann_path, out_shape):
  4. try:
  5. img = io.imread(root_old+"/"+img_path)
  6. except Exception as E:
  7. print E
  8. h, w, _ = img.shape
  9. f_h, f_w = float(out_shape)/h, float(out_shape)/w
  10. trans_img = transform.rescale(img, (f_h, f_w))
  11. num_objs = 0
  12. with open(root_old+"/"+ann_path, 'r') as f:
  13. ann = f.readline()
  14. ann = ann.rstrip()
  15. ann = ann.split(' ')
  16. ann = [float(i) for i in ann]
  17. num_objs = len(ann) / 5
  18. for idx in xrange(num_objs):
  19. ann[idx * 5 + 0] = int(f_w * ann[idx * 5 + 0])
  20. ann[idx * 5 + 1] = int(f_h * ann[idx * 5 + 1])
  21. ann[idx * 5 + 2] = int(f_w * ann[idx * 5 + 2])
  22. ann[idx * 5 + 3] = int(f_h * ann[idx * 5 + 3])
  23. # Write the new annotations to file
  24. with open(root_new+"/"+ann_path, 'w') as f_new:
  25. for val in ann:
  26. f_new.write(str(val)+' ')
  27. # Save the new image
  28. io.imwrite(root_new+"/"+img_path, trans_img)
  29. def preprocess():
  30. source = '/users2/Datasets/PASCAL_VOC/VOCdevkit/VOC2012_Resize/source.txt'
  31. root_old = '/users2/Datasets/PASCAL_VOC/VOCdevkit/VOC2012'
  32. root_new = '/users2/Datasets/PASCAL_VOC/VOCdevkit/VOC2012_Resize'
  33. out_shape = 416
  34. with open(source, 'r') as src:
  35. lines = src.readlines()
  36. print 'Processing {} images and annotations'.format(len(lines))
  37. for line in lines:
  38. line = line.rstrip()
  39. line = line.split(' ')
  40. img_path = line[0]
  41. ann_path = line[1]
  42. rescale(root_new, root_old, img_path, ann_path, out_shape)
  43. if __name__ == '__main__':
  44. preprocess()