creek
The AI Image Editor of 2030git clone https://github.com/maydayv7/creek
lib/utils/clip_image_processor.dart (1901B)
1import 'dart:typed_data';
2import 'dart:io';
3import 'package:image/image.dart' as img;
4
5class ClipImageProcessor {
6 // CLIP Standard Constants
7 static const List<double> mean = [0.48145466, 0.4578275, 0.40821073];
8 static const List<double> std = [0.26862954, 0.26130258, 0.27577711];
9
10 /// Reads file, resizes, crops, normalizes, and returns Float32List [1, 3, 224, 224]
11 static Future<Float32List?> preprocess(String filePath) async {
12 final bytes = await File(filePath).readAsBytes();
13 final image = img.decodeImage(bytes);
14
15 if (image == null) return null;
16
17 // 1. Resize (Shortest side to 224)
18 int w = image.width;
19 int h = image.height;
20 int target = 224;
21
22 img.Image resized;
23 if (w < h) {
24 resized = img.copyResize(image, width: target);
25 } else {
26 resized = img.copyResize(image, height: target);
27 }
28
29 // 2. Center Crop (224x224)
30 final cropped = img.copyResizeCropSquare(resized, size: target);
31
32 // 3. Convert to Float32 List (NCHW format: Batch, Channels, Height, Width)
33 // Size: 1 * 3 * 224 * 224 = 150,528 float values
34 final Float32List inputData = Float32List(1 * 3 * 224 * 224);
35
36 int pixelIndex = 0;
37 // Iterate pixels and separate channels
38 // Planar format (RRRR... GGGG... BBBB...)
39 int rOffset = 0;
40 int gOffset = 224 * 224;
41 int bOffset = 224 * 224 * 2;
42
43 for (var y = 0; y < 224; y++) {
44 for (var x = 0; x < 224; x++) {
45 final pixel = cropped.getPixel(x, y);
46
47 // Normalize: (Value/255 - Mean) / Std
48 double r = (pixel.r / 255.0 - mean[0]) / std[0];
49 double g = (pixel.g / 255.0 - mean[1]) / std[1];
50 double b = (pixel.b / 255.0 - mean[2]) / std[2];
51
52 inputData[rOffset + pixelIndex] = r;
53 inputData[gOffset + pixelIndex] = g;
54 inputData[bOffset + pixelIndex] = b;
55
56 pixelIndex++;
57 }
58 }
59
60 return inputData;
61 }
62}