Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

flickr.py 6.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
  1. import glob
  2. import os
  3. from collections import defaultdict
  4. from html.parser import HTMLParser
  5. from pathlib import Path
  6. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  7. from .folder import default_loader
  8. from .vision import VisionDataset
  9. class Flickr8kParser(HTMLParser):
  10. """Parser for extracting captions from the Flickr8k dataset web page."""
  11. def __init__(self, root: Union[str, Path]) -> None:
  12. super().__init__()
  13. self.root = root
  14. # Data structure to store captions
  15. self.annotations: Dict[str, List[str]] = {}
  16. # State variables
  17. self.in_table = False
  18. self.current_tag: Optional[str] = None
  19. self.current_img: Optional[str] = None
  20. def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
  21. self.current_tag = tag
  22. if tag == "table":
  23. self.in_table = True
  24. def handle_endtag(self, tag: str) -> None:
  25. self.current_tag = None
  26. if tag == "table":
  27. self.in_table = False
  28. def handle_data(self, data: str) -> None:
  29. if self.in_table:
  30. if data == "Image Not Found":
  31. self.current_img = None
  32. elif self.current_tag == "a":
  33. img_id = data.split("/")[-2]
  34. img_id = os.path.join(self.root, img_id + "_*.jpg")
  35. img_id = glob.glob(img_id)[0]
  36. self.current_img = img_id
  37. self.annotations[img_id] = []
  38. elif self.current_tag == "li" and self.current_img:
  39. img_id = self.current_img
  40. self.annotations[img_id].append(data.strip())
  41. class Flickr8k(VisionDataset):
  42. """`Flickr8k Entities <http://hockenmaier.cs.illinois.edu/8k-pictures.html>`_ Dataset.
  43. Args:
  44. root (str or ``pathlib.Path``): Root directory where images are downloaded to.
  45. ann_file (string): Path to annotation file.
  46. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  47. and returns a transformed version. E.g, ``transforms.RandomCrop``
  48. target_transform (callable, optional): A function/transform that takes in the
  49. target and transforms it.
  50. loader (callable, optional): A function to load an image given its path.
  51. By default, it uses PIL as its image loader, but users could also pass in
  52. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  53. """
  54. def __init__(
  55. self,
  56. root: Union[str, Path],
  57. ann_file: str,
  58. transform: Optional[Callable] = None,
  59. target_transform: Optional[Callable] = None,
  60. loader: Callable[[str], Any] = default_loader,
  61. ) -> None:
  62. super().__init__(root, transform=transform, target_transform=target_transform)
  63. self.ann_file = os.path.expanduser(ann_file)
  64. # Read annotations and store in a dict
  65. parser = Flickr8kParser(self.root)
  66. with open(self.ann_file) as fh:
  67. parser.feed(fh.read())
  68. self.annotations = parser.annotations
  69. self.ids = list(sorted(self.annotations.keys()))
  70. self.loader = loader
  71. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  72. """
  73. Args:
  74. index (int): Index
  75. Returns:
  76. tuple: Tuple (image, target). target is a list of captions for the image.
  77. """
  78. img_id = self.ids[index]
  79. # Image
  80. img = self.loader(img_id)
  81. if self.transform is not None:
  82. img = self.transform(img)
  83. # Captions
  84. target = self.annotations[img_id]
  85. if self.target_transform is not None:
  86. target = self.target_transform(target)
  87. return img, target
  88. def __len__(self) -> int:
  89. return len(self.ids)
  90. class Flickr30k(VisionDataset):
  91. """`Flickr30k Entities <https://bryanplummer.com/Flickr30kEntities/>`_ Dataset.
  92. Args:
  93. root (str or ``pathlib.Path``): Root directory where images are downloaded to.
  94. ann_file (string): Path to annotation file.
  95. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  96. and returns a transformed version. E.g, ``transforms.RandomCrop``
  97. target_transform (callable, optional): A function/transform that takes in the
  98. target and transforms it.
  99. loader (callable, optional): A function to load an image given its path.
  100. By default, it uses PIL as its image loader, but users could also pass in
  101. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  102. """
  103. def __init__(
  104. self,
  105. root: str,
  106. ann_file: str,
  107. transform: Optional[Callable] = None,
  108. target_transform: Optional[Callable] = None,
  109. loader: Callable[[str], Any] = default_loader,
  110. ) -> None:
  111. super().__init__(root, transform=transform, target_transform=target_transform)
  112. self.ann_file = os.path.expanduser(ann_file)
  113. # Read annotations and store in a dict
  114. self.annotations = defaultdict(list)
  115. with open(self.ann_file) as fh:
  116. for line in fh:
  117. img_id, caption = line.strip().split("\t")
  118. self.annotations[img_id[:-2]].append(caption)
  119. self.ids = list(sorted(self.annotations.keys()))
  120. self.loader = loader
  121. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  122. """
  123. Args:
  124. index (int): Index
  125. Returns:
  126. tuple: Tuple (image, target). target is a list of captions for the image.
  127. """
  128. img_id = self.ids[index]
  129. # Image
  130. filename = os.path.join(self.root, img_id)
  131. img = self.loader(filename)
  132. if self.transform is not None:
  133. img = self.transform(img)
  134. # Captions
  135. target = self.annotations[img_id]
  136. if self.target_transform is not None:
  137. target = self.target_transform(target)
  138. return img, target
  139. def __len__(self) -> int:
  140. return len(self.ids)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...