philippemo commited on
Commit
70f07a0
1 Parent(s): d64f300

Create extract_images.py

Browse files
Files changed (1) hide show
  1. extract_images.py +58 -0
extract_images.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from io import BytesIO
3
+ from PIL import Image
4
+ import argparse
5
+
6
+ import dask.dataframe as dd
7
+
8
+ def save_image(row, image_column, format, save_folder, print_logs):
9
+ row_id = row.name
10
+
11
+ try:
12
+ byte_string = row[image_column]
13
+ img = Image.open(BytesIO(byte_string))
14
+ img_path = os.path.join(save_folder, f'image_{row_id}.{format}')
15
+ img.save(img_path)
16
+ if print_logs:
17
+ print(f"Saving image to {img_path}")
18
+ except Exception as e:
19
+ return f'Error saving image for row {row_id}: {str(e)}'
20
+
21
+
22
+ def main():
23
+ parser = argparse.ArgumentParser(description='Download and save images from a Parquet file.')
24
+ parser.add_argument('--parquet_file',
25
+ type=str,
26
+ help='Path to the Parquet file or folder containing the images')
27
+ parser.add_argument('--save_folder',
28
+ type=str,
29
+ help='The folder where to save the images to')
30
+ parser.add_argument('--image_column',
31
+ type=str,
32
+ default="data",
33
+ required=False,
34
+ help='Name of the column containing image byte strings, defaults to "data"')
35
+ parser.add_argument('--format',
36
+ type=str,
37
+ default="jpg",
38
+ required=False,
39
+ help='Image format (e.g., png, jpg), defaults to "jpgs"')
40
+ parser.add_argument('--print_logs',
41
+ type=bool,
42
+ default=False,
43
+ required=False,
44
+ help='Flag to enable saving logs when writing images, defaults to False')
45
+ args = parser.parse_args()
46
+
47
+ ddf = dd.read_parquet(args.parquet_file)
48
+
49
+ results = ddf.apply(save_image, axis=1, meta='str',
50
+ image_column=args.image_column,
51
+ save_folder=args.save_folder,
52
+ format=args.format,
53
+ print_logs=args.print_logs)
54
+ results.compute()
55
+
56
+
57
+ if __name__ == "__main__":
58
+ main()