File size: 9,855 Bytes
77374e1
 
 
25df395
77374e1
 
 
25df395
77374e1
 
 
25df395
 
 
 
 
 
77374e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25df395
 
 
 
 
 
 
 
77374e1
 
 
 
25df395
 
 
 
77374e1
 
 
 
25df395
77374e1
 
 
 
25df395
77374e1
25df395
 
77374e1
 
 
 
 
 
 
 
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
let stream = null;
let corners = [];
let isManualAdjustment = false;
let cvReady = false;

function onOpenCvReady() {
    console.log('OpenCV.js is ready');
    cvReady = true;
}

function initCamera() {
    if (!cvReady) {
        console.warn('OpenCV.js not loaded yet, waiting...');
        setTimeout(initCamera, 100);
        return;
    }
const video = document.getElementById('cameraFeed');
    const canvas = document.getElementById('cameraCanvas');
    const processedCanvas = document.getElementById('processedCanvas');
    const captureBtn = document.getElementById('captureBtn');
    const retakeBtn = document.getElementById('retakeBtn');
    const confirmBtn = document.getElementById('confirmBtn');
    const processingScreen = document.getElementById('processingScreen');
    const cornerOverlay = document.getElementById('cornerOverlay');
    const processingIndicator = document.getElementById('processingIndicator');
    
    // Access camera
    navigator.mediaDevices.getUserMedia({ 
        video: {
            facingMode: 'environment',
            width: { ideal: 1920 },
            height: { ideal: 1080 }
        },
        audio: false 
    })
    .then(function(mediaStream) {
        stream = mediaStream;
        video.srcObject = mediaStream;
    })
    .catch(function(err) {
        console.error("Error accessing camera: ", err);
        alert("Could not access the camera. Please ensure you have granted camera permissions.");
    });
    
    // Capture photo
    captureBtn.addEventListener('click', function() {
        processingIndicator.classList.remove('hidden');
        
        // Wait a moment for better image quality
        setTimeout(() => {
            captureAndProcess(video, canvas, processedCanvas, cornerOverlay);
            processingIndicator.classList.add('hidden');
            processingScreen.classList.remove('hidden');
        }, 200);
    });
    
    // Retake photo
    retakeBtn.addEventListener('click', function() {
        processingScreen.classList.add('hidden');
    });
    
    // Confirm and save
    confirmBtn.addEventListener('click', function() {
        saveAndSend(processedCanvas);
    });
}

function captureAndProcess(video, canvas, processedCanvas, cornerOverlay) {
    // Set canvas dimensions to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    processedCanvas.width = video.videoWidth;
    processedCanvas.height = video.videoHeight;
    
    // Draw video frame to canvas
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    // Get image data
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    
    // Process with OpenCV
    try {
        const src = cv.matFromImageData(imageData);
        const dst = new cv.Mat();
        const gray = new cv.Mat();
        const edges = new cv.Mat();
        const hierarchy = new cv.Mat();
        
        // Convert to grayscale
        cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY);
        
        // Apply Gaussian blur
        cv.GaussianBlur(gray, gray, new cv.Size(5, 5), 0);
        
        // Edge detection
        cv.Canny(gray, edges, 75, 200);
        
        // Find contours
        let contours = new cv.MatVector();
        cv.findContours(edges, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE);
        
        // Find largest quadrilateral
        let maxArea = 0;
        let documentContour = null;
        
        for (let i = 0; i < contours.size(); ++i) {
            const contour = contours.get(i);
            const perimeter = cv.arcLength(contour, true);
            const approx = new cv.Mat();
            
            cv.approxPolyDP(contour, approx, 0.02 * perimeter, true);
            
            if (approx.rows === 4) {
                const area = cv.contourArea(approx);
                if (area > maxArea) {
                    maxArea = area;
                    documentContour = approx;
                }
            }
            approx.delete();
        }
        
        if (documentContour) {
            // Order points: top-left, top-right, bottom-right, bottom-left
            corners = orderPoints(documentContour.data32S);
            
            // Apply perspective transform
            const rect = getRectangleCorners(corners);
            const dstPoints = cv.matFromArray(4, 1, cv.CV_32FC2, rect);
            const srcPoints = cv.matFromArray(4, 1, cv.CV_32FC2, corners.flat());
            
            const M = cv.getPerspectiveTransform(srcPoints, dstPoints);
            cv.warpPerspective(src, dst, M, new cv.Size(canvas.width, canvas.height));
            
            // Draw on processed canvas
            const processedCtx = processedCanvas.getContext('2d');
            const processedImageData = new ImageData(
                new Uint8ClampedArray(dst.data),
                dst.cols,
                dst.rows
            );
            processedCanvas.width = dst.cols;
            processedCanvas.height = dst.rows;
            processedCtx.putImageData(processedImageData, 0, 0);
            
            // Show corner overlay for manual adjustment
            updateCornerOverlay(cornerOverlay, corners, canvas);
            cornerOverlay.classList.remove('hidden');
        } else {
            // No document found, just use original image
            const processedCtx = processedCanvas.getContext('2d');
            processedCtx.drawImage(canvas, 0, 0);
            alert("Could not detect document edges. Using full image.");
        }
        
        // Clean up
        src.delete();
        dst.delete();
        gray.delete();
        edges.delete();
        hierarchy.delete();
        contours.delete();
    } catch (err) {
        console.error("OpenCV error: ", err);
        // Fallback to original image if OpenCV fails
        const processedCtx = processedCanvas.getContext('2d');
        processedCtx.drawImage(canvas, 0, 0);
        alert("Error processing image. Using original capture.");
    }
}

function orderPoints(points) {
    // Convert points to array of {x, y}
    const pts = [
        {x: points[0], y: points[1]},
        {x: points[2], y: points[3]},
        {x: points[4], y: points[5]},
        {x: points[6], y: points[7]}
    ];
    
    // Sort by y-coordinate to get top and bottom
    pts.sort((a, b) => a.y - b.y);
    
    // Top-left has smaller x, top-right has larger x
    const top = pts.slice(0, 2).sort((a, b) => a.x - b.x);
    const bottom = pts.slice(2, 4).sort((a, b) => a.x - b.x);
    
    return [
        top[0],  // top-left
        top[1],  // top-right
        bottom[1], // bottom-right
        bottom[0]  // bottom-left
    ];
}

function getRectangleCorners(corners) {
    // Calculate width (max of top and bottom widths)
    const widthTop = Math.hypot(corners[1].x - corners[0].x, corners[1].y - corners[0].y);
    const widthBottom = Math.hypot(corners[2].x - corners[3].x, corners[2].y - corners[3].y);
    const maxWidth = Math.max(widthTop, widthBottom);
    
    // Calculate height (max of left and right heights)
    const heightLeft = Math.hypot(corners[3].x - corners[0].x, corners[3].y - corners[0].y);
    const heightRight = Math.hypot(corners[2].x - corners[1].x, corners[2].y - corners[1].y);
    const maxHeight = Math.max(heightLeft, heightRight);
    
    return [
        0, 0,  // top-left
        maxWidth, 0,  // top-right
        maxWidth, maxHeight,  // bottom-right
        0, maxHeight   // bottom-left
    ];
}

function updateCornerOverlay(overlay, corners, canvas) {
    const corner1 = document.getElementById('corner1');
    const corner2 = document.getElementById('corner2');
    const corner3 = document.getElementById('corner3');
    const corner4 = document.getElementById('corner4');
    
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    
    // Position corner markers
    corner1.style.left = `${corners[0].x / scaleX}px`;
    corner1.style.top = `${corners[0].y / scaleY}px`;
    
    corner2.style.left = `${corners[1].x / scaleX}px`;
    corner2.style.top = `${corners[1].y / scaleY}px`;
    
    corner3.style.left = `${corners[2].x / scaleX}px`;
    corner3.style.top = `${corners[2].y / scaleY}px`;
    
    corner4.style.left = `${corners[3].x / scaleX}px`;
    corner4.style.top = `${corners[3].y / scaleY}px`;
}

function saveAndSend(canvas) {
    // Convert canvas to blob
    canvas.toBlob(function(blob) {
        const formData = new FormData();
        formData.append('document', blob, 'document_' + Date.now() + '.jpg');
        
        // Send to server
        // For demo purposes, we'll simulate a successful upload
        console.log('Document captured successfully (simulated)');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1000);
        
        // In a real app, you would use:
        /*
        fetch('upload.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('Upload failed');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                window.location.href = 'index.html';
            } else {
                throw new Error(data.message || 'Upload failed');
            }
        })
        .catch(error => {
            console.error('Upload error:', error);
            alert('Error uploading document: ' + error.message);
        });
        */
}, 'image/jpeg', 0.9);
}

// Clean up camera stream when navigating away
window.addEventListener('beforeunload', function() {
    if (stream) {
        stream.getTracks().forEach(track => track.stop());
    }
});