CSE526/Presentation/snippets/blur.ts
2024-04-24 22:01:13 -04:00

86 lines
2.7 KiB
TypeScript

// Blur function
function blurImage1(inImage: Uint8Array): Uint8Array {
const numRows = Math.sqrt(inImage.length);
const numCols = numRows;
const blurx = new Uint8Array(numRows * numCols);
const blury = new Uint8Array(numRows * numCols);
// Blur in the x-direction
for (let x = 1; x < numCols - 1; x++) {
for (let y = 0; y < numRows; y++) {
const index = y * numCols + x;
blurx[index] = Math.floor((inImage[y * numCols + (x - 1)] + inImage[y * numCols + x] + inImage[y * numCols + (x + 1)]) / 3);
}
}
// Blur in the y-direction
for (let x = 0; x < numCols; x++) {
for (let y = 1; y < numRows - 1; y++) {
const index = y * numCols + x;
blury[index] = Math.floor((blurx[(y - 1) * numCols + x] + blurx[y * numCols + x] + blurx[(y + 1) * numCols + x]) / 3);
}
}
return blury;
}
function blurImage2(inImage: Uint8Array): Uint8Array {
const numRows = Math.sqrt(inImage.length);
const numCols = numRows;
const blurx = new Uint8Array(numRows * numCols);
const blury = new Uint8Array(numRows * numCols);
// Blur in the x-direction
for (let y = 0; y < numRows; y++) {
for (let x = 1; x < numCols - 1; x++) {
const index = y * numCols + x;
blurx[index] = Math.floor((inImage[y * numCols + (x - 1)] + inImage[y * numCols + x] + inImage[y * numCols + (x + 1)]) / 3);
}
}
// Blur in the y-direction
for (let y = 1; y < numRows - 1; y++) {
for (let x = 0; x < numCols; x++) {
const index = y * numCols + x;
blury[index] = Math.floor((blurx[(y - 1) * numCols + x] + blurx[y * numCols + x] + blurx[(y + 1) * numCols + x]) / 3);
}
}
return blury;
}
// Sample input
const numRows = 1024;
const numCols = 1024;
const inputImage = new Uint8Array(numRows * numCols);
// Initialize input image with random values (0-255)
for (let i = 0; i < numRows * numCols; i++) {
inputImage[i] = Math.floor(Math.random() * 256);
}
// Run the blurImage2 function 100 times and measure the runtime
const startTime2 = Date.now();
for (let i = 0; i < 100; i++) {
blurImage2(inputImage);
}
const endTime2 = Date.now();
// Run the blurImage1 function 100 times and measure the runtime
const startTime1 = Date.now();
for (let i = 0; i < 100; i++) {
blurImage1(inputImage);
}
const endTime1 = Date.now();
// Calculate total runtime
const totalTime1 = endTime1 - startTime1;
// Calculate total runtime
const totalTime2 = endTime2 - startTime2;
console.log(`Total runtime for first blur algorithm is: ${totalTime1} ms`);
console.log(`Total runtime for second blur algorithm is: ${totalTime2} ms`);