File size: 1,923 Bytes
b801a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
license: mit
dataset_info:
  features:
  - name: image
    dtype:
      array3_d:
        shape:
        - 512
        - 512
        - 3
        dtype: uint8
  - name: filename
    dtype: string
  splits:
  - name: train
    num_bytes: 34195458528
    num_examples: 18614
  download_size: 6667979906
  dataset_size: 34195458528
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train-*
---
```
from datasets import load_dataset
from PIL import Image
import numpy as np
import os
from tqdm import tqdm

# 加载数据集
dataset_path = "path_to/style_fonts_img"
dataset = load_dataset(dataset_path)

# 创建保存目录
save_dir = os.path.join(dataset_path, "extracted_images")
os.makedirs(save_dir, exist_ok=True)

# 获取数据集大小
total_samples = len(dataset['train'])
print(f"数据集共有 {total_samples} 个样本")

# 使用tqdm创建进度条
for i, example in tqdm(enumerate(dataset['train']), total=total_samples, desc="处理图像"):
    try:
        # 获取图像数据
        image_array = example['image']
        
        # 转换为PIL图像
        image = Image.fromarray(np.uint8(image_array))
        
        # 获取文件名
        filename = example['filename'] 
        
        # 保存图像
        image_path = os.path.join(save_dir, filename)
        image.save(image_path)
        
        # 保存文本
        if 'text' in example and example['text']:
            text_filename = os.path.splitext(filename)[0] + '.txt'
            text_path = os.path.join(text_dir, text_filename)
            with open(text_path, 'w', encoding='utf-8') as f:
                f.write(example['text'])
        
        # print(f"已保存 {filename}")
        
        # 只处理前10个样本(可选)
        if i >= 9:
            break
            
    except Exception as e:
        print(f"处理样本 {i} 时出错: {e}")

print("处理完成!")
```