File size: 1,465 Bytes
ed9f15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * Image Utilities - Helper functions for image manipulation

 */

import { DETECTION_CONFIG } from '../config.js';

/**

 * Load image from data URL or path

 */
export function loadImage(src) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = src;
    });
}

/**

 * Crop image region with optional padding

 */
export async function cropImage(img, x1, y1, x2, y2, padding = DETECTION_CONFIG.yolo.padding) {
    const width = x2 - x1;
    const height = y2 - y1;
    const padX = width * padding;
    const padY = height * padding;
    
    x1 = Math.max(0, x1 - padX);
    y1 = Math.max(0, y1 - padY);
    x2 = Math.min(img.width, x2 + padX);
    y2 = Math.min(img.height, y2 + padY);
    
    const canvas = document.createElement('canvas');
    canvas.width = x2 - x1;
    canvas.height = y2 - y1;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, x1, y1, x2 - x1, y2 - y1, 0, 0, x2 - x1, y2 - y1);
    
    return canvas.toDataURL();
}

/**

 * Read file as data URL

 */
export function readFileAsDataURL(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}