📷
画像処理100本ノックに挑戦|Laplacianフィルタ(017/100)
これはなに?
画像処理100本ノックを、TypeScriptとlibvipsで挑戦してみる記事の17本目です。
前回
実装
お題
Laplacianフィルタを実装せよ。
Laplacian(ラプラシアン)フィルタとは輝度の二次微分をとることでエッジ検出を行うフィルタである。
デジタル画像は離散データであるので、x方向・y方向の一次微分は、それぞれ次式で表される。
Ix(x,y) = (I(x+1, y) - I(x,y)) / ((x+1)-x) = I(x+1, y) - I(x,y)
Iy(x,y) = (I(x, y+1) - I(x,y)) / ((y+1)-y) = I(x, y+1) - I(x,y)
さらに二次微分は、次式で表される。
Ixx(x,y) = (Ix(x,y) - Ix(x-1,y)) / ((x+1)-x) = Ix(x,y) - Ix(x-1,y)
= (I(x+1, y) - I(x,y)) - (I(x, y) - I(x-1,y))
= I(x+1,y) - 2 * I(x,y) + I(x-1,y)
Iyy(x,y) = ... = I(x,y+1) - 2 * I(x,y) + I(x,y-1)
これらより、ラプラシアン は次式で定義される。
D^2 I(x,y) = Ixx(x,y) + Iyy(x,y)
= I(x-1,y) + I(x,y-1) - 4 * I(x,y) + I(x+1,y) + I(x,y+1)
これをカーネル化すると、次のようになる。
0 1 0
K = [ 1 -4 1 ]
0 1 0
Coding
import sharp from 'sharp';
export async function laplacianFilter(
inputPath: string,
outputPath: string,
kernelSize: number = 3
): Promise<void> {
try {
// まずグレースケールに変換
const image = await sharp(inputPath)
.raw()
.toBuffer({ resolveWithObject: true });
const { data, info } = image;
const { width, height, channels } = info;
// グレースケール変換
const grayData = Buffer.alloc(width * height);
for (let i = 0; i < data.length; i += channels) {
const b = data[i];
const g = data[i + 1];
const r = data[i + 2];
const gray = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b);
grayData[i / channels] = gray;
}
// パディングサイズを計算
const pad = Math.floor(kernelSize / 2);
// パディング付きの配列を作成
const paddedHeight = height + 2 * pad;
const paddedWidth = width + 2 * pad;
const paddedData = new Float32Array(paddedHeight * paddedWidth);
const tempData = new Float32Array(paddedHeight * paddedWidth);
// ゼロパディング
for (let y = 0; y < paddedHeight; y++) {
for (let x = 0; x < paddedWidth; x++) {
const destPos = y * paddedWidth + x;
if (y >= pad && y < paddedHeight - pad &&
x >= pad && x < paddedWidth - pad) {
const srcY = y - pad;
const srcX = x - pad;
const srcPos = srcY * width + srcX;
paddedData[destPos] = grayData[srcPos];
tempData[destPos] = grayData[srcPos];
}
}
}
// Laplacianカーネルの定義
const kernel = [
[0, 1, 0],
[1, -4, 1],
[0, 1, 0]
];
// 結果用の配列を作成
const result = Buffer.alloc(width * height);
// フィルタリング
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let sum = 0;
// カーネル領域の処理
for (let ky = 0; ky < kernelSize; ky++) {
for (let kx = 0; kx < kernelSize; kx++) {
const py = y + ky;
const px = x + kx;
const pixel = tempData[py * paddedWidth + px];
sum += pixel * kernel[ky][kx];
}
}
// 結果を保存(0-255の範囲にクリップ)
const pos = y * width + x;
// お手本と同じように、絶対値を取らずにクリップする
result[pos] = Math.min(255, Math.max(0, sum));
}
}
// 結果を保存
await sharp(result, {
raw: {
width,
height,
channels: 1
}
})
.toFile(outputPath);
console.log('Laplacianフィルタ処理が完了しました');
} catch (error) {
console.error('画像処理中にエラーが発生しました:', error);
throw error;
}
}
Test
import { existsSync, unlinkSync } from 'fs';
import { join } from 'path';
import sharp from 'sharp';
import { laplacianFilter } from './imageProcessor';
describe('Laplacian Filter Tests', () => {
const testInputPath = join(__dirname, '../test-images/test.jpeg');
const testOutputPath = join(__dirname, '../test-images/test-laplacian.jpg');
afterEach(() => {
if (existsSync(testOutputPath)) {
unlinkSync(testOutputPath);
}
});
test('should successfully apply Laplacian filter', async () => {
await expect(laplacianFilter(testInputPath, testOutputPath))
.resolves.not.toThrow();
expect(existsSync(testOutputPath)).toBe(true);
});
test('should maintain image dimensions', async () => {
await laplacianFilter(testInputPath, testOutputPath);
const inputMetadata = await sharp(testInputPath).metadata();
const outputMetadata = await sharp(testOutputPath).metadata();
expect(outputMetadata.width).toBe(inputMetadata.width);
expect(outputMetadata.height).toBe(inputMetadata.height);
});
test('should detect edges', async () => {
await laplacianFilter(testInputPath, testOutputPath);
const outputImage = await sharp(testOutputPath)
.raw()
.toBuffer({ resolveWithObject: true });
// エッジと非エッジ領域の両方が存在することを確認
let hasEdges = false;
let hasNonEdges = false;
for (let i = 0; i < outputImage.data.length; i++) {
const value = outputImage.data[i];
if (value > 30) hasEdges = true;
if (value < 10) hasNonEdges = true;
if (hasEdges && hasNonEdges) break;
}
expect(hasEdges).toBe(true);
expect(hasNonEdges).toBe(true);
});
test('should have valid pixel values', async () => {
await laplacianFilter(testInputPath, testOutputPath);
const outputImage = await sharp(testOutputPath)
.raw()
.toBuffer({ resolveWithObject: true });
// すべてのピクセル値が有効な範囲内にあることを確認
const isValidValue = (value: number) => value >= 0 && value <= 255;
expect(Array.from(outputImage.data).every(isValidValue)).toBe(true);
});
});
結果
入力 | 出力 |
---|---|
![]() |
![]() |
Discussion