You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.3 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Functions for importing/exporting Object Detection categories."""
  16. import csv
  17. import tensorflow as tf
  18. def load_categories_from_csv_file(csv_path):
  19. """Loads categories from a csv file.
  20. The CSV file should have one comma delimited numeric category id and string
  21. category name pair per line. For example:
  22. 0,"cat"
  23. 1,"dog"
  24. 2,"bird"
  25. ...
  26. Args:
  27. csv_path: Path to the csv file to be parsed into categories.
  28. Returns:
  29. categories: A list of dictionaries representing all possible categories.
  30. The categories will contain an integer 'id' field and a string
  31. 'name' field.
  32. Raises:
  33. ValueError: If the csv file is incorrectly formatted.
  34. """
  35. categories = []
  36. with tf.gfile.Open(csv_path, 'r') as csvfile:
  37. reader = csv.reader(csvfile, delimiter=',', quotechar='"')
  38. for row in reader:
  39. if not row:
  40. continue
  41. if len(row) != 2:
  42. raise ValueError('Expected 2 fields per row in csv: %s' % ','.join(row))
  43. category_id = int(row[0])
  44. category_name = row[1]
  45. categories.append({'id': category_id, 'name': category_name})
  46. return categories
  47. def save_categories_to_csv_file(categories, csv_path):
  48. """Saves categories to a csv file.
  49. Args:
  50. categories: A list of dictionaries representing categories to save to file.
  51. Each category must contain an 'id' and 'name' field.
  52. csv_path: Path to the csv file to be parsed into categories.
  53. """
  54. categories.sort(key=lambda x: x['id'])
  55. with tf.gfile.Open(csv_path, 'w') as csvfile:
  56. writer = csv.writer(csvfile, delimiter=',', quotechar='"')
  57. for category in categories:
  58. writer.writerow([category['id'], category['name']])