Spaces:
Running
Running
File size: 10,473 Bytes
1f2f6bf 00fddb0 1f2f6bf 00fddb0 1f2f6bf 00fddb0 1f2f6bf 00fddb0 1f2f6bf 65cf3e9 70cd90e 65cf3e9 70cd90e 1f2f6bf 70cd90e 419db65 70cd90e 419db65 70cd90e 419db65 70cd90e 419db65 70cd90e 1f2f6bf 419db65 1f2f6bf 419db65 65cf3e9 1f2f6bf 419db65 1f2f6bf 65cf3e9 1f2f6bf 70cd90e 1f2f6bf 419db65 1f2f6bf 419db65 65cf3e9 1f2f6bf 419db65 1f2f6bf 65cf3e9 1f2f6bf 70cd90e 419db65 70cd90e 419db65 70cd90e 419db65 70cd90e 65cf3e9 70cd90e 65cf3e9 70cd90e 65cf3e9 70cd90e 65cf3e9 1f2f6bf 70cd90e 419db65 65cf3e9 1f2f6bf 65cf3e9 1f2f6bf 419db65 1f2f6bf 65cf3e9 1f2f6bf 65cf3e9 1f2f6bf 70cd90e 65cf3e9 1f2f6bf 70cd90e 65cf3e9 1f2f6bf | 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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | import { useEffect, useMemo, useState } from "react";
const MAX_SIZE: number = 500;
function getBoundedDimensions(width: number, height: number): [number, number] {
if (width <= MAX_SIZE && height <= MAX_SIZE) {
return [width, height];
}
const scale = Math.min(MAX_SIZE / width, MAX_SIZE / height);
const boundedWidth = Math.max(1, Math.round(width * scale));
const boundedHeight = Math.max(1, Math.round(height * scale));
return [boundedWidth, boundedHeight];
}
async function getImageData(imageUrl: string): Promise<ImageData> {
const image = await new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = imageUrl;
})
const sourceWidth = image.naturalWidth || image.width;
const sourceHeight = image.naturalHeight || image.height;
const [targetWidth, targetHeight] = getBoundedDimensions(sourceWidth, sourceHeight);
const canvas = document.createElement("canvas")
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("Failed to get canvas context");
}
ctx.drawImage(image, 0, 0, targetWidth, targetHeight);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
function getImageUrl(imageData: ImageData): string {
const canvas = document.createElement("canvas");
canvas.width = imageData.width;
canvas.height = imageData.height;
const ctx = canvas.getContext("2d")
if (!ctx) {
throw new Error("Failed to get canvas context");
}
ctx.putImageData(imageData, 0, 0);
return canvas.toDataURL("image/png");
}
function convertToGrayscale(imageData: ImageData): ImageData {
const output = new ImageData(
new Uint8ClampedArray(imageData.data),
imageData.width,
imageData.height,
);
const data = output.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const gray = 0.299 * r + 0.587 * g + 0.114 * b;
data[i] = data[i + 1] = data[i + 2] = gray;
}
return output;
}
export type ConvolutionRange = {
min: number;
max: number;
};
type ConvolutionResult = ConvolutionRange & {
values: Float32Array;
width: number;
height: number;
channels: 1 | 3;
};
function getShape(array: number[][] | number[][][]): number[] {
const shape: number[] = [];
let current: unknown = array;
while (Array.isArray(current)) {
shape.push(current.length);
current = current[0];
}
return shape;
}
function convolve(
imageData: ImageData,
kernel: number[][] | number[][][],
useColor: boolean,
stride: number,
dilation: number,
padding: number,
): ConvolutionResult {
if (Array.isArray(kernel[0][0])) { // 3D kernel
console.log('3D kernel', getShape(kernel))
return convolveColor(imageData, kernel as number[][][], stride, dilation, padding);
} else { // 2D kernel
console.log('2D kernel', getShape(kernel))
if (useColor) {
return convolveColorDepthwise(imageData, kernel as number[][], stride, dilation, padding);
} {
return convolveGray(imageData, kernel as number[][], stride, dilation, padding);
}
}
}
function convolveGray(image: ImageData, kernel: number[][], stride: number, dilation: number, padding: number): ConvolutionResult {
const kernelWidth = kernel[0].length;
const kernelHeight = kernel.length;
const width = image.width;
const height = image.height;
const inputData = image.data;
const outputWidth = Math.max(1, Math.floor((width + 2 * padding - dilation * (kernelWidth - 1) - 1) / stride) + 1);
const outputHeight = Math.max(1, Math.floor((height + 2 * padding - dilation * (kernelHeight - 1) - 1) / stride) + 1);
const values = new Float32Array(outputWidth * outputHeight);
let min = Infinity;
let max = -Infinity;
for (let y = 0; y < outputHeight; ++y) {
for (let x = 0; x < outputWidth; ++x) {
// dot product
let sum = 0;
for (let ky = 0; ky < kernelHeight; ++ky) {
for (let kx = 0; kx < kernelWidth; ++kx) {
const sourceX = x * stride - padding + kx * dilation;
const sourceY = y * stride - padding + ky * dilation;
if (sourceX < 0 || sourceX >= width || sourceY < 0 || sourceY >= height) continue;
const pixelIndex = (sourceY * width + sourceX) * 4;
const pixelValue = inputData[pixelIndex];
const kernelValue = kernel[ky][kx];
sum += pixelValue * kernelValue;
}
}
values[y * outputWidth + x] = sum;
min = Math.min(min, sum);
max = Math.max(max, sum);
}
}
return { values, width: outputWidth, height: outputHeight, channels: 1, min, max };
}
function convolveColor(image: ImageData, kernel: number[][][], stride: number, dilation: number, padding: number): ConvolutionResult {
const kernelWidth = kernel[0][0].length;
const kernelHeight = kernel[0].length;
const width = image.width;
const height = image.height;
const inputData = image.data;
const outputWidth = Math.max(1, Math.floor((width + 2 * padding - dilation * (kernelWidth - 1) - 1) / stride) + 1);
const outputHeight = Math.max(1, Math.floor((height + 2 * padding - dilation * (kernelHeight - 1) - 1) / stride) + 1);
const values = new Float32Array(outputWidth * outputHeight);
let min = Infinity;
let max = -Infinity;
for (let y = 0; y < outputHeight; ++y) {
for (let x = 0; x < outputWidth; ++x) {
// dot product over 3 channels
let sum = 0;
for (let ky = 0; ky < kernelHeight; ++ky) {
for (let kx = 0; kx < kernelWidth; ++kx) {
const sourceX = x * stride - padding + kx * dilation;
const sourceY = y * stride - padding + ky * dilation;
if (sourceX < 0 || sourceX >= width || sourceY < 0 || sourceY >= height) continue;
const pixelIndex = (sourceY * width + sourceX) * 4;
const r = inputData[pixelIndex];
const g = inputData[pixelIndex + 1];
const b = inputData[pixelIndex + 2];
const kernelR = kernel[0][ky][kx];
const kernelG = kernel[1][ky][kx];
const kernelB = kernel[2][ky][kx];
sum += r * kernelR + g * kernelG + b * kernelB;
}
}
values[y * outputWidth + x] = sum;
min = Math.min(min, sum);
max = Math.max(max, sum);
}
}
return { values, width: outputWidth, height: outputHeight, channels: 1, min, max };
}
function convolveColorDepthwise(image: ImageData, kernel: number[][], stride: number, dilation: number, padding: number): ConvolutionResult {
const kernelWidth = kernel[0].length;
const kernelHeight = kernel.length;
const outputWidth = Math.max(1, Math.floor((image.width + 2 * padding - dilation * (kernelWidth - 1) - 1) / stride) + 1);
const outputHeight = Math.max(1, Math.floor((image.height + 2 * padding - dilation * (kernelHeight - 1) - 1) / stride) + 1);
const values = new Float32Array(outputWidth * outputHeight * 3);
let min = Infinity;
let max = -Infinity;
console.log('here');
for (let y = 0; y < outputHeight; ++y) {
for (let x = 0; x < outputWidth; ++x) {
for (let channel = 0; channel < 3; ++channel) {
let sum = 0;
for (let ky = 0; ky < kernelHeight; ++ky) {
for (let kx = 0; kx < kernelWidth; ++kx) {
const sourceX = x * stride - padding + kx * dilation;
const sourceY = y * stride - padding + ky * dilation;
if (sourceX < 0 || sourceX >= image.width || sourceY < 0 || sourceY >= image.height) continue;
const pixelIndex = (sourceY * image.width + sourceX) * 4 + channel;
sum += image.data[pixelIndex] * kernel[ky][kx];
}
}
values[(y * outputWidth + x) * 3 + channel] = sum;
min = Math.min(min, sum);
max = Math.max(max, sum);
}
}
}
console.log('done', outputHeight, outputWidth);
return { values, width: outputWidth, height: outputHeight, channels: 3, min, max };
}
function convolutionToImageData(result: ConvolutionResult): ImageData {
const outputData = new Uint8ClampedArray(result.width * result.height * 4);
const range = result.max - result.min;
const pixelCount = result.width * result.height;
for (let i = 0; i < pixelCount; ++i) {
const outputIndex = i * 4;
for (let channel = 0; channel < 3; ++channel) {
const rawValue = (result.channels === 1)
? result.values[i]
: result.values[i * 3 + channel];
outputData[outputIndex + channel] = (range === 0)
? 0
: 255 * (rawValue - result.min) / range;
}
outputData[outputIndex + 3] = 255;
}
console.log('conversion done');
return new ImageData(outputData, result.width, result.height);
}
export default function useConvolutionProcessing(
rawInputImage: string,
kernel: number[][][] | number[][],
useColor: boolean,
stride: number,
dilation: number,
padding: number,
): [string | null, string | null, ConvolutionRange | null] {
const [rawImageData, setRawImageData] = useState<ImageData | null>(null);
// extract input image data (array)
useEffect(() => {
let cancelled = false;
async function processImage() {
const imageData = await getImageData(rawInputImage);
if (!cancelled) {
setRawImageData(imageData);
}
}
processImage();
return () => {
cancelled = true;
}
}, [rawInputImage]);
const processedImageData = useMemo(() => {
if (!rawImageData) return null;
return useColor ? rawImageData : convertToGrayscale(rawImageData);
}, [rawImageData, useColor]);
const convolutionResult = useMemo(() => {
if (!processedImageData) return null;
return convolve(processedImageData, kernel, useColor, stride, dilation, padding);
}, [processedImageData, kernel, useColor, stride, dilation, padding]);
const inputImage = useMemo(() => {
if (!processedImageData) return null;
return getImageUrl(processedImageData);
}, [processedImageData]);
const outputImage = useMemo(() => {
if (!convolutionResult) return null;
return getImageUrl(convolutionToImageData(convolutionResult));
}, [convolutionResult]);
console.log('url');
const outputRange = convolutionResult
? { min: convolutionResult.min, max: convolutionResult.max }
: null;
console.log('range');
return [inputImage, outputImage, outputRange];
}
|