Download mobileCamera.js from fenkod2001/docsnap-smart-document-scanner: direct link, hf CLI and curl.
- Browser
- Download file 9.86 kB
-
https://huggingface.co/spaces/fenkod2001/docsnap-smart-document-scanner/resolve/main/mobileCamera.js
- Command line
-
hf download hf://spaces/fenkod2001/docsnap-smart-document-scanner/mobileCamera.js
-
curl -L -o mobileCamera.js https://huggingface.co/spaces/fenkod2001/docsnap-smart-document-scanner/resolve/main/mobileCamera.js
9.86 kB
| 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()); | |
| } | |
| }); |