-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathDatasetExporter.java
More file actions
1457 lines (1206 loc) · 57.2 KB
/
DatasetExporter.java
File metadata and controls
1457 lines (1206 loc) · 57.2 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*Copyright ©2025 APIJSON(https://github.com/APIJSON)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
package apijson;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
public class DatasetExporter {
/**
* 验证COCO数据集类型
*/
public static boolean isValidCocoType(String type) {
return Arrays.asList("detection", "classification", "segmentation",
"keypoints", "face_keypoints", "rotated", "ocr").contains(type);
}
/**
* 创建COCO数据集目录结构
*/
public static void createCocoDirectoryStructure(String baseDir, String type) throws IOException {
// 创建基础目录
Files.createDirectories(Paths.get(baseDir + "annotations"));
Files.createDirectories(Paths.get(baseDir + "images"));
// 根据类型创建特定目录
switch (type) {
case "rotated":
case "ocr":
Files.createDirectories(Paths.get(baseDir + "labels"));
break;
default:
// detection, classification, segmentation, keypoints, face_keypoints使用标准结构
break;
}
}
/**
* 生成COCO数据集文件
*/
public static void generateCocoDataset(String baseDir, String type, String datasetName) throws IOException {
switch (type) {
case "detection":
generateDetectionDataset(baseDir, datasetName);
break;
case "classification":
generateClassificationDataset(baseDir, datasetName);
break;
case "segmentation":
generateSegmentationDataset(baseDir, datasetName);
break;
case "keypoints":
generateKeypointsDataset(baseDir, datasetName);
break;
case "face_keypoints":
generateFaceKeypointsDataset(baseDir, datasetName);
break;
case "rotated":
generateRotatedDataset(baseDir, datasetName);
break;
case "ocr":
generateOCRDataset(baseDir, datasetName);
break;
}
}
/**
* 生成检测数据集
*/
public static void generateDetectionDataset(String baseDir, String datasetName) throws IOException {
// 创建annotations JSON文件
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createDetectionCategories());
root.put("images", createMockImages(10));
root.put("annotations", createDetectionAnnotations(10));
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
// 创建README
createReadmeFile(baseDir, datasetName, "detection");
}
/**
* 生成分类数据集
*/
public static void generateClassificationDataset(String baseDir, String datasetName) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createClassificationCategories());
root.put("images", createMockImages(10));
root.put("annotations", createClassificationAnnotations(10));
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "classification");
}
/**
* 生成分割数据集
*/
public static void generateSegmentationDataset(String baseDir, String datasetName) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createSegmentationCategories());
root.put("images", createMockImages(10));
root.put("annotations", createSegmentationAnnotations(10));
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "segmentation");
}
/**
* 生成姿态关键点数据集
*/
public static void generateKeypointsDataset(String baseDir, String datasetName) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createKeypointsCategories());
root.put("images", createMockImages(10));
root.put("annotations", createKeypointsAnnotations(10));
writeJsonFile(baseDir + "annotations/person_keypoints_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "keypoints");
}
/**
* 生成人脸关键点数据集
*/
public static void generateFaceKeypointsDataset(String baseDir, String datasetName) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createFaceKeypointsCategories());
root.put("images", createMockImages(10));
root.put("annotations", createFaceKeypointsAnnotations(10));
writeJsonFile(baseDir + "annotations/face_keypoints_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "face_keypoints");
}
/**
* 生成旋转检测数据集
*/
public static void generateRotatedDataset(String baseDir, String datasetName) throws IOException {
// JSON格式
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("categories", createRotatedCategories());
root.put("images", createMockImages(10));
root.put("annotations", createRotatedAnnotations(10));
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
// TXT格式标签文件
for (int i = 1; i <= 10; i++) {
String txtContent = "320 240 200 100 30 1\n280 180 150 80 45 2\n";
writeTextFile(baseDir + "labels/000" + i + ".txt", txtContent);
}
createReadmeFile(baseDir, datasetName, "rotated");
}
/**
* 生成OCR数据集
*/
public static void generateOCRDataset(String baseDir, String datasetName) throws IOException {
// JSON格式
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
root.put("images", createMockImages(10));
root.put("annotations", createOCRAnnotations(10));
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
// TXT格式标签文件
for (int i = 1; i <= 10; i++) {
String txtContent = "100,200,220,200,220,240,100,240,Hello World\n";
writeTextFile(baseDir + "labels/000" + i + ".txt", txtContent);
}
createReadmeFile(baseDir, datasetName, "ocr");
}
/**
* 从APIJSON查询结果生成COCO数据集
* @param baseDir 基础目录
* @param type 数据集类型
* @param datasetName 数据集名称
* @param apiJsonData APIJSON查询结果数据列表
* @throws IOException
*/
public static void generateCocoDatasetFromApiJson(String baseDir, String type, String datasetName, List<JSONObject> apiJsonData) throws IOException {
switch (type) {
case "detection":
generateDetectionDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "classification":
generateClassificationDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "segmentation":
generateSegmentationDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "keypoints":
generateKeypointsDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "face_keypoints":
generateFaceKeypointsDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "rotated":
generateRotatedDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
case "ocr":
generateOCRDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
default:
// 默认使用检测格式
generateDetectionDatasetFromApiJson(baseDir, datasetName, apiJsonData);
break;
}
}
/**
* 从APIJSON数据生成检测数据集
*/
private static void generateDetectionDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
// 从数据中提取类别信息
JSONArray categories = extractCategoriesFromApiJson(apiJsonData);
root.put("categories", categories);
// 转换图片信息
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
// 转换标注信息
JSONArray annotations = convertApiJsonToDetectionAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "detection");
}
/**
* 从APIJSON数据生成分类数据集
*/
private static void generateClassificationDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray categories = extractCategoriesFromApiJson(apiJsonData);
root.put("categories", categories);
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToClassificationAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "classification");
}
/**
* 从APIJSON数据生成分割数据集
*/
private static void generateSegmentationDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray categories = extractCategoriesFromApiJson(apiJsonData);
root.put("categories", categories);
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToSegmentationAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "segmentation");
}
/**
* 从APIJSON数据生成关键点数据集
*/
private static void generateKeypointsDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray categories = createKeypointsCategories();
root.put("categories", categories);
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToKeypointsAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/person_keypoints_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "keypoints");
}
/**
* 从APIJSON数据生成人脸关键点数据集
*/
private static void generateFaceKeypointsDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray categories = createFaceKeypointsCategories();
root.put("categories", categories);
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToFaceKeypointsAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/face_keypoints_" + datasetName + ".json", root);
createReadmeFile(baseDir, datasetName, "face_keypoints");
}
/**
* 从APIJSON数据生成旋转检测数据集
*/
private static void generateRotatedDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray categories = extractCategoriesFromApiJson(apiJsonData);
root.put("categories", categories);
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToRotatedAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
// 生成TXT格式的标签文件
generateRotatedLabelFiles(baseDir, apiJsonData);
createReadmeFile(baseDir, datasetName, "rotated");
}
/**
* 从APIJSON数据生成OCR数据集
*/
private static void generateOCRDatasetFromApiJson(String baseDir, String datasetName, List<JSONObject> apiJsonData) throws IOException {
JSONObject root = new JSONObject();
root.put("info", createCocoInfo(datasetName));
root.put("licenses", new JSONArray());
JSONArray images = convertApiJsonToImages(apiJsonData);
root.put("images", images);
JSONArray annotations = convertApiJsonToOCRAnnotations(apiJsonData);
root.put("annotations", annotations);
writeJsonFile(baseDir + "annotations/instances_" + datasetName + ".json", root);
// 生成TXT格式的标签文件
generateOCRLabelFiles(baseDir, apiJsonData);
createReadmeFile(baseDir, datasetName, "ocr");
}
// ===== 辅助方法 =====
public static JSONObject createCocoInfo(String datasetName) {
JSONObject info = new JSONObject();
info.put("description", datasetName + " Dataset");
info.put("url", "https://example.com");
info.put("version", "1.0");
info.put("year", 2024);
info.put("contributor", "APIJSON");
info.put("date_created", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
return info;
}
public static JSONArray createDetectionCategories() {
JSONArray categories = new JSONArray();
JSONObject cat1 = new JSONObject();
cat1.put("id", 1);
cat1.put("name", "car");
cat1.put("supercategory", "vehicle");
categories.add(cat1);
JSONObject cat2 = new JSONObject();
cat2.put("id", 2);
cat2.put("name", "person");
cat2.put("supercategory", "human");
categories.add(cat2);
return categories;
}
public static JSONArray createClassificationCategories() {
JSONArray categories = new JSONArray();
JSONObject cat1 = new JSONObject();
cat1.put("id", 1);
cat1.put("name", "dog");
categories.add(cat1);
JSONObject cat2 = new JSONObject();
cat2.put("id", 2);
cat2.put("name", "cat");
categories.add(cat2);
return categories;
}
public static JSONArray createSegmentationCategories() {
return createDetectionCategories(); // 复用检测的类别定义
}
public static JSONArray createKeypointsCategories() {
JSONArray categories = new JSONArray();
JSONObject cat = new JSONObject();
cat.put("id", 1);
cat.put("name", "person");
cat.put("keypoints", Arrays.asList("nose", "left_eye", "right_eye", "left_ear", "right_ear",
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
"left_wrist", "right_wrist", "left_hip", "right_hip",
"left_knee", "right_knee", "left_ankle", "right_ankle"));
cat.put("skeleton", new JSONArray()); // 骨架连接关系
categories.add(cat);
return categories;
}
public static JSONArray createFaceKeypointsCategories() {
JSONArray categories = new JSONArray();
JSONObject cat = new JSONObject();
cat.put("id", 1);
cat.put("name", "face");
// 68个脸部关键点名称
List<String> keypoints = new ArrayList<>();
for (int i = 1; i <= 68; i++) {
keypoints.add("p" + i);
}
cat.put("keypoints", keypoints);
cat.put("skeleton", new JSONArray());
categories.add(cat);
return categories;
}
public static JSONArray createRotatedCategories() {
JSONArray categories = new JSONArray();
JSONObject cat1 = new JSONObject();
cat1.put("id", 1);
cat1.put("name", "plane");
categories.add(cat1);
JSONObject cat2 = new JSONObject();
cat2.put("id", 2);
cat2.put("name", "ship");
categories.add(cat2);
return categories;
}
public static JSONArray createMockImages(int count) {
JSONArray images = new JSONArray();
for (int i = 1; i <= count; i++) {
JSONObject img = new JSONObject();
img.put("id", i);
img.put("file_name", String.format("000%03d.jpg", i));
img.put("height", 480 + (i % 3) * 100); // 变化的高度
img.put("width", 640 + (i % 2) * 200); // 变化的宽度
images.add(img);
}
return images;
}
public static JSONArray createDetectionAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
// 每张图片1-3个标注
int annCount = 1 + (i % 3);
for (int j = 0; j < annCount; j++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
ann.put("category_id", (j % 2) + 1);
ann.put("bbox", Arrays.asList(100 + j*50, 150 + j*30, 200, 100));
ann.put("area", 20000);
ann.put("iscrowd", 0);
annotations.add(ann);
}
}
return annotations;
}
public static JSONArray createClassificationAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", i);
ann.put("image_id", i);
ann.put("category_id", (i % 2) + 1);
annotations.add(ann);
}
return annotations;
}
public static JSONArray createSegmentationAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
ann.put("category_id", (i % 2) + 1);
// 多边形分割
JSONArray segmentation = new JSONArray();
segmentation.add(Arrays.asList(100, 150, 300, 150, 300, 250, 100, 250));
ann.put("segmentation", segmentation);
ann.put("bbox", Arrays.asList(100, 150, 200, 100));
ann.put("area", 20000);
ann.put("iscrowd", 0);
annotations.add(ann);
}
return annotations;
}
public static JSONArray createKeypointsAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
ann.put("category_id", 1);
ann.put("bbox", Arrays.asList(100, 150, 200, 400));
ann.put("num_keypoints", 17);
// 17个关键点 (x, y, visibility)
List<Integer> keypoints = new ArrayList<>();
for (int k = 0; k < 17; k++) {
keypoints.add(120 + k * 10); // x
keypoints.add(200 + k * 15); // y
keypoints.add(2); // visibility
}
ann.put("keypoints", keypoints);
annotations.add(ann);
}
return annotations;
}
public static JSONArray createFaceKeypointsAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
ann.put("category_id", 1);
ann.put("bbox", Arrays.asList(120, 150, 200, 200));
ann.put("num_keypoints", 68);
// 68个脸部关键点
List<Integer> keypoints = new ArrayList<>();
for (int k = 0; k < 68; k++) {
keypoints.add(100 + k * 2); // x
keypoints.add(150 + k * 1); // y
keypoints.add(2); // visibility
}
ann.put("keypoints", keypoints);
annotations.add(ann);
}
return annotations;
}
public static JSONArray createRotatedAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
ann.put("category_id", (i % 2) + 1);
// 旋转框: [cx, cy, w, h, angle]
ann.put("bbox", Arrays.asList(320, 240, 200, 100, 30));
annotations.add(ann);
}
return annotations;
}
public static JSONArray createOCRAnnotations(int imageCount) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int i = 1; i <= imageCount; i++) {
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", i);
// 多边形边界框
JSONArray segmentation = new JSONArray();
segmentation.add(Arrays.asList(100, 200, 220, 200, 220, 240, 100, 240));
ann.put("segmentation", segmentation);
ann.put("bbox", Arrays.asList(100, 200, 120, 40));
ann.put("text", "Hello World");
ann.put("language", "en");
ann.put("legibility", "legible");
annotations.add(ann);
}
return annotations;
}
public static void writeJsonFile(String filePath, JSONObject content) throws IOException {
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(content.toJSONString());
}
}
public static void writeTextFile(String filePath, String content) throws IOException {
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(content);
}
}
public static void createReadmeFile(String baseDir, String datasetName, String type) throws IOException {
String content = "# " + datasetName + " Dataset\n\n" +
"Type: " + type + "\n" +
"Generated: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n\n" +
"## Directory Structure:\n" +
"- annotations/: JSON annotation files\n" +
"- images/: Image files (placeholder)\n" +
"- labels/: TXT label files (for rotated/ocr types)\n\n" +
"## Usage:\n" +
"1. Replace placeholder images in images/ directory\n" +
"2. Update annotation files with real data\n" +
"3. Train your model with this dataset\n";
writeTextFile(baseDir + "README.md", content);
}
public static void createZipFromDirectory(String sourceDir, String zipPath) throws IOException {
// 使用Java原生ZIP压缩
try (FileOutputStream fos = new FileOutputStream(zipPath);
java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos)) {
File sourceFile = new File(sourceDir);
addFilesToZip(sourceFile, sourceFile.getName(), zos);
}
}
public static void addFilesToZip(File file, String fileName, java.util.zip.ZipOutputStream zos) throws IOException {
if (file.isDirectory()) {
if (!fileName.endsWith("/")) {
fileName += "/";
}
zos.putNextEntry(new java.util.zip.ZipEntry(fileName));
zos.closeEntry();
File[] files = file.listFiles();
if (files != null) {
for (File childFile : files) {
addFilesToZip(childFile, fileName + childFile.getName(), zos);
}
}
} else {
zos.putNextEntry(new java.util.zip.ZipEntry(fileName));
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
}
}
public static void deleteDirectory(File directory) throws IOException {
if (directory.exists()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
file.delete();
}
}
}
directory.delete();
}
}
// ===== 数据转换辅助方法 =====
/**
* 从APIJSON数据中提取类别信息
*/
private static JSONArray extractCategoriesFromApiJson(List<JSONObject> apiJsonData) {
JSONArray categories = new JSONArray();
Set<String> categorySet = new HashSet<>();
for (JSONObject item : apiJsonData) {
if (item == null) continue;
JSONObject testRecord = item.getJSONObject("TestRecord");
if (testRecord == null) continue;
String responseStr = testRecord.getString("response");
if (responseStr == null) continue;
try {
JSONObject responseObj = JSONObject.parseObject(responseStr);
JSONArray bboxes = responseObj.getJSONArray("bboxes");
if (bboxes != null) {
for (int i = 0; i < bboxes.size(); i++) {
JSONObject bbox = bboxes.getJSONObject(i);
if (bbox != null) {
String label = bbox.getString("label");
if (label != null && !categorySet.contains(label)) {
categorySet.add(label);
JSONObject category = new JSONObject();
category.put("id", categories.size() + 1);
category.put("name", label);
category.put("supercategory", "object");
categories.add(category);
}
}
}
}
} catch (Exception e) {
// 解析失败,跳过
continue;
}
}
// 如果没有找到类别,使用默认类别
if (categories.isEmpty()) {
JSONObject defaultCategory = new JSONObject();
defaultCategory.put("id", 1);
defaultCategory.put("name", "object");
defaultCategory.put("supercategory", "object");
categories.add(defaultCategory);
}
return categories;
}
/**
* 将APIJSON数据转换为COCO格式的images数组
*/
private static JSONArray convertApiJsonToImages(List<JSONObject> apiJsonData) {
JSONArray images = new JSONArray();
for (int i = 0; i < apiJsonData.size(); i++) {
JSONObject item = apiJsonData.get(i);
if (item == null) continue;
JSONObject random = item.getJSONObject("Random");
if (random == null) continue;
JSONObject image = new JSONObject();
image.put("id", i + 1);
image.put("file_name", random.getString("file"));
image.put("width", random.getIntValue("width"));
image.put("height", random.getIntValue("height"));
images.add(image);
}
return images;
}
/**
* 将APIJSON数据转换为检测标注
*/
private static JSONArray convertApiJsonToDetectionAnnotations(List<JSONObject> apiJsonData) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int imageId = 0; imageId < apiJsonData.size(); imageId++) {
JSONObject item = apiJsonData.get(imageId);
if (item == null) continue;
JSONObject testRecord = item.getJSONObject("TestRecord");
if (testRecord == null) continue;
String responseStr = testRecord.getString("response");
if (responseStr == null) continue;
try {
JSONObject responseObj = JSONObject.parseObject(responseStr);
JSONArray bboxes = responseObj.getJSONArray("bboxes");
if (bboxes != null) {
for (int j = 0; j < bboxes.size(); j++) {
JSONObject bboxData = bboxes.getJSONObject(j);
if (bboxData == null) continue;
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", imageId + 1);
// 查找类别ID
String label = bboxData.getString("label");
int categoryId = findCategoryId(label, apiJsonData);
ann.put("category_id", categoryId);
// 设置bbox
JSONArray bbox = bboxData.getJSONArray("bbox");
if (bbox != null && bbox.size() >= 4) {
ann.put("bbox", Arrays.asList(
bbox.getDouble(0), bbox.getDouble(1),
bbox.getDouble(2), bbox.getDouble(3)
));
ann.put("area", bbox.getDouble(2) * bbox.getDouble(3));
}
ann.put("iscrowd", 0);
annotations.add(ann);
}
}
} catch (Exception e) {
// 解析失败,跳过
continue;
}
}
return annotations;
}
/**
* 将APIJSON数据转换为分类标注
*/
private static JSONArray convertApiJsonToClassificationAnnotations(List<JSONObject> apiJsonData) {
JSONArray annotations = new JSONArray();
for (int imageId = 0; imageId < apiJsonData.size(); imageId++) {
JSONObject item = apiJsonData.get(imageId);
if (item == null) continue;
JSONObject testRecord = item.getJSONObject("TestRecord");
if (testRecord == null) continue;
String responseStr = testRecord.getString("response");
if (responseStr == null) continue;
try {
JSONObject responseObj = JSONObject.parseObject(responseStr);
JSONArray bboxes = responseObj.getJSONArray("bboxes");
if (bboxes != null && !bboxes.isEmpty()) {
JSONObject bboxData = bboxes.getJSONObject(0); // 取第一个检测结果
if (bboxData != null) {
JSONObject ann = new JSONObject();
ann.put("id", imageId + 1);
ann.put("image_id", imageId + 1);
String label = bboxData.getString("label");
int categoryId = findCategoryId(label, apiJsonData);
ann.put("category_id", categoryId);
annotations.add(ann);
}
}
} catch (Exception e) {
continue;
}
}
return annotations;
}
/**
* 将APIJSON数据转换为分割标注
*/
private static JSONArray convertApiJsonToSegmentationAnnotations(List<JSONObject> apiJsonData) {
JSONArray annotations = new JSONArray();
int annId = 1;
for (int imageId = 0; imageId < apiJsonData.size(); imageId++) {
JSONObject item = apiJsonData.get(imageId);
if (item == null) continue;
JSONObject testRecord = item.getJSONObject("TestRecord");
if (testRecord == null) continue;
String responseStr = testRecord.getString("response");
if (responseStr == null) continue;
try {
JSONObject responseObj = JSONObject.parseObject(responseStr);
// 处理多边形分割
JSONArray polygons = responseObj.getJSONArray("polygons");
if (polygons != null) {
for (int j = 0; j < polygons.size(); j++) {
JSONObject polygonData = polygons.getJSONObject(j);
if (polygonData == null) continue;
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", imageId + 1);
String label = polygonData.getString("label");
int categoryId = findCategoryId(label, apiJsonData);
ann.put("category_id", categoryId);
// 设置分割多边形
JSONArray points = polygonData.getJSONArray("points");
if (points != null) {
JSONArray segmentation = new JSONArray();
segmentation.add(points);
ann.put("segmentation", segmentation);
// 计算bbox
double[] bbox = calculatePolygonBbox(points);
ann.put("bbox", Arrays.asList(bbox[0], bbox[1], bbox[2], bbox[3]));
ann.put("area", bbox[2] * bbox[3]);
}
ann.put("iscrowd", 0);
annotations.add(ann);
}
}
// 如果没有多边形数据,使用bbox数据
else {
JSONArray bboxes = responseObj.getJSONArray("bboxes");
if (bboxes != null) {
for (int j = 0; j < bboxes.size(); j++) {
JSONObject bboxData = bboxes.getJSONObject(j);
if (bboxData == null) continue;
JSONObject ann = new JSONObject();
ann.put("id", annId++);
ann.put("image_id", imageId + 1);
String label = bboxData.getString("label");
int categoryId = findCategoryId(label, apiJsonData);
ann.put("category_id", categoryId);
JSONArray bbox = bboxData.getJSONArray("bbox");
if (bbox != null && bbox.size() >= 4) {
ann.put("bbox", Arrays.asList(
bbox.getDouble(0), bbox.getDouble(1),
bbox.getDouble(2), bbox.getDouble(3)
));
ann.put("area", bbox.getDouble(2) * bbox.getDouble(3));
}
ann.put("iscrowd", 0);
annotations.add(ann);
}
}
}
} catch (Exception e) {