Ai-image-enhancer / index.html
Koko2011's picture
Upload 2 files
06f05e5 verified
Raw
History Blame Contribute Delete
19.9 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>advanced ai image enhancer</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<style>
:root {
--bg-color: #121212; --surface-color: #1e1e1e; --primary-color: #03dac6;
--on-primary-color: #000000; --text-color: #e0e0e0; --border-color: #333333;
}
body {
font-family: -apple-system, blinkmacsystemfont, "segoe ui", roboto, helvetica, arial, sans-serif;
background-color: var(--bg-color); color: var(--text-color); margin: 0;
display: flex; flex-direction: column; align-items: center; justify-content: center;
min-height: 100vh; padding: 20px; box-sizing: border-box;
}
h1 { color: var(--primary-color); text-align: center; }
.container {
width: 100%; max-width: 900px; background-color: var(--surface-color);
border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);
padding: 2rem; box-sizing: border-box;
}
.app-state { display: none; }
body.state-loading #loadingstate, body.state-upload #uploadstate,
body.state-pre-process #preprocessstate, body.state-processing #processingstate,
body.state-results #resultsstate { display: block; }
#loadingstate, #processingstate { text-align: center; }
.spinner {
border: 4px solid rgba(255, 255, 255, 0.2); border-left-color: var(--primary-color);
border-radius: 50%; width: 40px; height: 40px;
animation: spin 1s linear infinite; margin: 20px auto;
}
@keyframes spin { to { transform: rotate(360deg); } }
#drop-area {
border: 2px dashed var(--border-color); border-radius: 8px; padding: 40px;
text-align: center; transition: background-color 0.2s, border-color 0.2s; cursor: pointer;
}
#drop-area.highlight { background-color: rgba(3, 218, 198, 0.1); border-color: var(--primary-color); }
#drop-area p { margin: 0; font-size: 1.2rem; }
.btn {
display: inline-block; background-color: var(--primary-color); color: var(--on-primary-color);
padding: 12px 24px; border-radius: 6px; border: none; font-weight: bold;
margin-top: 20px; cursor: pointer; transition: opacity 0.2s;
}
.btn:hover { opacity: 0.9; }
#fileelem { display: none; }
#progressbarcontainer { width: 100%; background-color: var(--border-color); border-radius: 4px; overflow: hidden; margin-top: 20px; }
#progressbar { width: 0%; height: 20px; background-color: var(--primary-color); transition: width 0.3s ease-in-out; }
.comparison-container { position: relative; width: 100%; overflow: hidden; border-radius: 8px; }
.comparison-container canvas { display: block; width: 100%; height: auto; }
#outputcanvas { position: absolute; top: 0; left: 0; clip-path: polygon(0 0, 50% 0, 50% 100%, 0 100%); }
.slider { position: absolute; top: 0; left: 50%; width: 4px; height: 100%; background-color: rgba(255, 255, 255, 0.7); cursor: ew-resize; transform: translatex(-50%); }
.slider-handle { position: absolute; top: 50%; left: 50%; width: 40px; height: 40px; border: 2px solid white; border-radius: 50%; background-color: var(--primary-color); transform: translate(-50%, -50%); display: flex; align-items: center; justify-content: space-evenly; }
.slider-handle::before, .slider-handle::after { content: ''; width: 0; height: 0; border-top: 6px solid transparent; border-bottom: 6px solid transparent; }
.slider-handle::before { border-right: 8px solid var(--on-primary-color); } .slider-handle::after { border-left: 8px solid var(--on-primary-color); }
.controls { margin-top: 20px; display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }
#preprocessstate canvas { max-width: 100%; border-radius: 8px; margin-top: 15px; }
.blur-controls { display: flex; flex-direction: column; align-items: center; gap: 10px; margin-top: 20px; }
</style>
</head>
<body class="state-loading">
<div class="container">
<h1>ai image enhancer</h1>
<div id="loadingstate" class="app-state"><p>loading ai model...</p><div class="spinner"></div><p id="modelerror" style="color: #cf6679; display: none;"></p></div>
<div id="uploadstate" class="app-state">
<input type="file" id="fileelem" accept="image/*">
<div id="drop-area"><p>drag & drop image here</p><p>or</p><label for="fileelem" class="btn">choose a file</label></div>
</div>
<div id="preprocessstate" class="app-state">
<p>your uploaded image:</p>
<canvas id="preprocesscanvas"></canvas>
<div class="blur-controls">
<label for="blurslider">blur radius: <span id="blurvalue">0</span>px</label>
<input type="range" id="blurslider" min="0" max="10" value="0" step="0.1" style="width: 80%;">
</div>
<div class="controls">
<button id="enhanceblurredbtn" class="btn">enhance blurred image</button>
<button id="enhanceoriginalbtn" class="btn">enhance original</button>
</div>
</div>
<div id="processingstate" class="app-state"><p>enhancing image, please wait...</p><div id="progressbarcontainer"><div id="progressbar"></div></div><p id="progresstext">0%</p></div>
<div id="resultsstate" class="app-state">
<p style="text-align:center;">slide to compare before vs. after</p>
<div class="comparison-container" id="comparisoncontainer"><canvas id="inputcanvas"></canvas><canvas id="outputcanvas"></canvas><div class="slider" id="slider"><div class="slider-handle"></div></div></div>
<div class="controls"><button id="downloadbtn" class="btn">download enhanced image</button><button id="resetbtn" class="btn">enhance another</button></div>
</div>
</div>
<script>
const tile_size = 256;
const overlap_size = 32; // Pixels to overlap on each side
const effective_tile_size = tile_size - 2 * overlap_size; // The non-overlapping part
const dom = {
body: document.body, droparea: document.getElementById('drop-area'), fileelem: document.getElementById('fileelem'),
progressbar: document.getElementById('progressbar'), progresstext: document.getElementById('progresstext'),
modelerrortext: document.getElementById('modelerror'), inputcanvas: document.getElementById('inputcanvas'),
outputcanvas: document.getElementById('outputcanvas'), comparisoncontainer: document.getElementById('comparisoncontainer'),
slider: document.getElementById('slider'), downloadbtn: document.getElementById('downloadbtn'), resetbtn: document.getElementById('resetbtn'),
preprocesscanvas: document.getElementById('preprocesscanvas'), blurslider: document.getElementById('blurslider'),
blurvalue: document.getElementById('blurvalue'), enhanceblurredbtn: document.getElementById('enhanceblurredbtn'),
enhanceoriginalbtn: document.getElementById('enhanceoriginalbtn')
};
let session, originalimage;
function setappstate(state) { dom.body.className = `state-${state}`; }
async function initmodel() {
try {
session = await ort.InferenceSession.create("./model.onnx");
setappstate('upload');
} catch (error) {
dom.modelerrortext.textContent = `Error: Failed to load model. Make sure 'model.onnx' is in the same directory as this HTML file and you are running a local server. Details: ${error.message}`;
dom.modelerrortext.style.display = 'block';
}
}
function getimagetensor(ctx, x, y, width = tile_size, height = tile_size) {
const imageData = ctx.getImageData(x, y, width, height);
const { data } = imageData;
const float32Data = new Float32Array(3 * width * height);
for (let i = 0; i < width * height; i++) {
float32Data[i] = data[i * 4] / 255.0;
float32Data[i + width * height] = data[i * 4 + 1] / 255.0;
float32Data[i + 2 * width * height] = data[i * 4 + 2] / 255.0;
}
return new ort.Tensor("float32", float32Data, [1, 3, height, width]);
}
function putimagetensor(ctx, x, y, tensor, width = tile_size, height = tile_size) {
const outputData = tensor.data;
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < width * height; i++) {
imageData.data[i * 4] = Math.max(0, Math.min(255, outputData[i] * 255));
imageData.data[i * 4 + 1] = Math.max(0, Math.min(255, outputData[i + width * height] * 255));
imageData.data[i * 4 + 2] = Math.max(0, Math.min(255, outputData[i + 2 * width * height] * 255));
imageData.data[i * 4 + 3] = 255;
}
ctx.putImageData(imageData, x, y);
}
// New blending function
function blendpixels(targetData, sourceData, index, alpha) {
targetData[index] = targetData[index] * (1 - alpha) + sourceData[index] * alpha;
targetData[index + 1] = targetData[index + 1] * (1 - alpha) + sourceData[index + 1] * alpha;
targetData[index + 2] = targetData[index + 2] * (1 - alpha) + sourceData[index + 2] * alpha;
targetData[index + 3] = 255; // Alpha channel
}
async function enhanceimage(sourcecanvas) {
setappstate('processing');
await new Promise(r => setTimeout(r, 100)); // Allow UI to update
const originalWidth = sourcecanvas.width;
const originalHeight = sourcecanvas.height;
// Calculate padded dimensions to ensure full coverage with effective_tile_size
const numTilesX = Math.ceil(originalWidth / effective_tile_size);
const numTilesY = Math.ceil(originalHeight / effective_tile_size);
const paddedWidth = numTilesX * effective_tile_size + 2 * overlap_size;
const paddedHeight = numTilesY * effective_tile_size + 2 * overlap_size;
const paddedInputCanvas = document.createElement('canvas');
paddedInputCanvas.width = paddedWidth;
paddedInputCanvas.height = paddedHeight;
const paddedInputCtx = paddedInputCanvas.getContext('2d');
// Draw the original image centered within the padded canvas
paddedInputCtx.drawImage(sourcecanvas, overlap_size, overlap_size, originalWidth, originalHeight);
const paddedOutputCanvas = document.createElement('canvas');
paddedOutputCanvas.width = paddedWidth;
paddedOutputCanvas.height = paddedHeight;
const paddedOutputCtx = paddedOutputCanvas.getContext('2d');
const totalTiles = numTilesX * numTilesY;
let processedTiles = 0;
for (let y_idx = 0; y_idx < numTilesY; y_idx++) {
for (let x_idx = 0; x_idx < numTilesX; x_idx++) {
// Calculate the top-left corner for extracting the *overlapping* input tile
let inputTileX = x_idx * effective_tile_size;
let inputTileY = y_idx * effective_tile_size;
// Ensure we don't go out of bounds for the input tile extraction
inputTileX = Math.min(inputTileX, paddedWidth - tile_size);
inputTileY = Math.min(inputTileY, paddedHeight - tile_size);
const tensor = getimagetensor(paddedInputCtx, inputTileX, inputTileY, tile_size, tile_size);
const results = await session.run({ input: tensor });
const outputTensor = results.output;
// Get the output tile as ImageData
const outputTileImageData = paddedOutputCtx.createImageData(tile_size, tile_size);
for (let i = 0; i < tile_size * tile_size; i++) {
outputTileImageData.data[i * 4] = Math.max(0, Math.min(255, outputTensor.data[i] * 255));
outputTileImageData.data[i * 4 + 1] = Math.max(0, Math.min(255, outputTensor.data[i + tile_size * tile_size] * 255));
outputTileImageData.data[i * 4 + 2] = Math.max(0, Math.min(255, outputTensor.data[i + 2 * tile_size * tile_size] * 255));
outputTileImageData.data[i * 4 + 3] = 255;
}
// Calculate the top-left corner for placing the *effective* part of the output tile
const outputPlacementX = x_idx * effective_tile_size;
const outputPlacementY = y_idx * effective_tile_size;
// Get the current image data from the padded output canvas for blending
const currentImageData = paddedOutputCtx.getImageData(outputPlacementX, outputPlacementY, effective_tile_size + overlap_size * 2, effective_tile_size + overlap_size * 2); // Get a larger area for blending
// Iterate over the output tile data and blend it into the padded output canvas
for (let yy = 0; yy < tile_size; yy++) {
for (let xx = 0; xx < tile_size; xx++) {
const globalX = outputPlacementX + xx;
const globalY = outputPlacementY + yy;
// Check bounds relative to the padded output canvas
if (globalX >= paddedWidth || globalY >= paddedHeight || globalX < 0 || globalY < 0) continue;
const outputTilePixelIndex = (yy * tile_size + xx) * 4;
const globalPixelIndex = ((globalY) * paddedWidth + (globalX)) * 4;
let alpha = 1.0; // Default to full opacity
// Horizontal blending (left side)
if (xx < overlap_size && x_idx > 0) {
alpha *= (xx / overlap_size);
}
// Horizontal blending (right side)
if (xx >= tile_size - overlap_size && x_idx < numTilesX - 1) {
alpha *= ((tile_size - 1 - xx) / overlap_size);
}
// Vertical blending (top side)
if (yy < overlap_size && y_idx > 0) {
alpha *= (yy / overlap_size);
}
// Vertical blending (bottom side)
if (yy >= tile_size - overlap_size && y_idx < numTilesY - 1) {
alpha *= ((tile_size - 1 - yy) / overlap_size);
}
// Apply blending
if (alpha < 1.0) {
// Read existing pixel data from the paddedOutputCtx to blend with
const existingPixelData = paddedOutputCtx.getImageData(globalX, globalY, 1, 1).data;
outputTileImageData.data[outputTilePixelIndex] = Math.round(existingPixelData[0] * (1 - alpha) + outputTileImageData.data[outputTilePixelIndex] * alpha);
outputTileImageData.data[outputTilePixelIndex + 1] = Math.round(existingPixelData[1] * (1 - alpha) + outputTileImageData.data[outputTilePixelIndex + 1] * alpha);
outputTileImageData.data[outputTilePixelIndex + 2] = Math.round(existingPixelData[2] * (1 - alpha) + outputTileImageData.data[outputTilePixelIndex + 2] * alpha);
}
}
}
paddedOutputCtx.putImageData(outputTileImageData, outputPlacementX, outputPlacementY);
processedTiles++;
const progress = Math.round((processedTiles / totalTiles) * 100);
dom.progressbar.style.width = `${progress}%`;
dom.progresstext.textContent = `${progress}%`;
await new Promise(resolve => setTimeout(resolve, 0));
}
}
dom.inputcanvas.width = originalWidth;
dom.inputcanvas.height = originalHeight;
dom.inputcanvas.getContext('2d').drawImage(sourcecanvas, 0, 0);
// Draw the effectively enhanced part from the padded output canvas onto the final output canvas
dom.outputcanvas.width = originalWidth;
dom.outputcanvas.height = originalHeight;
dom.outputcanvas.getContext('2d').drawImage(paddedOutputCanvas, overlap_size, overlap_size, originalWidth, originalHeight, 0, 0, originalWidth, originalHeight);
setappstate('results');
}
function applyblurpreview() {
const radius = dom.blurslider.value;
dom.blurvalue.textContent = radius;
const ctx = dom.preprocesscanvas.getContext('2d');
ctx.clearRect(0, 0, dom.preprocesscanvas.width, dom.preprocesscanvas.height);
ctx.filter = `blur(${radius}px)`;
ctx.drawImage(originalimage, 0, 0);
ctx.filter = 'none';
}
function handlefiles(files) {
const file = files[0];
if (!file || !file.type.startsWith('image/')) return alert('Please upload a valid image file.');
const img = new Image();
img.onload = () => {
originalimage = img;
const ctx = dom.preprocesscanvas.getContext('2d');
dom.preprocesscanvas.width = img.width;
dom.preprocesscanvas.height = img.height;
ctx.drawImage(img, 0, 0);
dom.blurslider.value = 0;
dom.blurvalue.textContent = '0';
setappstate('pre-process');
};
img.src = URL.createObjectURL(file);
}
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(ename => dom.droparea.addEventListener(ename, e => { e.preventDefault(); e.stopPropagation(); }));
['dragenter', 'dragover'].forEach(ename => dom.droparea.addEventListener(ename, () => dom.droparea.classList.add('highlight')));
['dragleave', 'drop'].forEach(ename => dom.droparea.addEventListener(ename, () => dom.droparea.classList.remove('highlight')));
dom.droparea.addEventListener('drop', e => handlefiles(e.dataTransfer.files));
dom.fileelem.addEventListener('change', e => handlefiles(e.target.files));
dom.downloadbtn.addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'enhanced_image.png';
link.href = dom.outputcanvas.toDataURL('image/png');
link.click();
});
dom.resetbtn.addEventListener('click', () => {
setappstate('upload');
dom.slider.style.left = '50%';
dom.outputcanvas.style.clipPath = 'polygon(0 0, 50% 0, 50% 100%, 0 100%)';
});
dom.blurslider.addEventListener('input', applyblurpreview);
dom.enhanceblurredbtn.addEventListener('click', () => {
const blurredcanvas = document.createElement('canvas');
blurredcanvas.width = originalimage.width;
blurredcanvas.height = originalimage.height;
const ctx = blurredcanvas.getContext('2d');
ctx.filter = `blur(${dom.blurslider.value}px)`;
ctx.drawImage(originalimage, 0, 0);
enhanceimage(blurredcanvas);
});
dom.enhanceoriginalbtn.addEventListener('click', () => enhanceimage(dom.preprocesscanvas));
let isdragging = false;
const moveslider = (clientX) => {
if (!isdragging) return;
const rect = dom.comparisoncontainer.getBoundingClientRect();
let x = clientX - rect.left;
x = Math.max(0, Math.min(x, rect.width));
const percent = (x / rect.width) * 100;
dom.slider.style.left = `${percent}%`;
dom.outputcanvas.style.clipPath = `polygon(0 0, ${percent}% 0, ${percent}% 100%, 0 100%)`;
};
dom.slider.addEventListener('mousedown', () => isdragging = true);
document.addEventListener('mouseup', () => isdragging = false);
document.addEventListener('mousemove', e => moveslider(e.clientX));
dom.slider.addEventListener('touchstart', e => { isdragging = true; e.preventDefault(); });
document.addEventListener('touchend', () => isdragging = false);
document.addEventListener('touchmove', e => moveslider(e.touches[0].clientX));
initmodel();
</script>
</body>
</html>