影像處理是現代技術中的重要應用之一,廣泛用於影像分析、計算機視覺和人工智慧。本文使用 TypeScript 編寫一些影像處理的基本操作,包括灰度轉換、去除邊框、提取有效區域和影像分割等。這些操作基於 HTML5 Canvas,實現起來直觀且高效。
環境準備
首先確保你有基礎的 TypeScript 專案,專案中需要一個 HTML 檔案和一個 TypeScript 檔案。HTML 檔案中的 Canvas 元素將用於顯示影像:
html
載入影像
首先在 Canvas 中載入影像:
typescript
const canvas = document.getElementById('imageCanvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d')!;
function loadImage(src: string): Promise
return new Promise((resolve, reject) => {
const img = new Image();
img.src = src;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
resolve();
};
img.onerror = reject;
});
}
灰度轉換
灰度轉換是影像處理中最常用的操作之一。以下函式將影像轉換為灰度:
typescript
function convertToGray(): void {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const gray = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
data[i] = data[i + 1] = data[i + 2] = gray;
}
ctx.putImageData(imageData, 0, 0);
}
去除影像邊框
去除邊框可以將影像的邊界部分設定為白色:
typescript
function clearBorders(borderWidth: number): void {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
if (x < borderWidth || y < borderWidth || x >= canvas.width - borderWidth || y >= canvas.height - borderWidth) {
const index = (y * canvas.width + x) * 4;
data[index] = data[index + 1] = data[index + 2] = 255;
}
}
}
ctx.putImageData(imageData, 0, 0);
}
提取有效區域
提取有效區域是為了找到影像中的主要內容區域。以下程式碼遍歷影像,找到所有畫素值低於灰度閾值的區域:
typescript
function getValidRegion(threshold: number): ImageData {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
let minX = canvas.width, minY = canvas.height, maxX = 0, maxY = 0;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
const index = (y * canvas.width + x) * 4;
const gray = data[index];
if (gray < threshold) {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
}
const width = maxX - minX + 1;
const height = maxY - minY + 1;
return ctx.getImageData(minX, minY, width, height);
}
影像分割
影像分割將影像按行列切分為多個小塊。以下程式碼實現水平和垂直分割:
typescript
function splitImage(rows: number, cols: number): ImageData[] {
const width = canvas.width / cols;
const height = canvas.height / rows;
const images: ImageData[] = [];
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const imageData = ctx.getImageData(col * width, row * height, width, height);
images.push(imageData);
}
}
return images;
}
生成二進位制編碼
生成二進位制編碼串,可以將影像中的灰度值轉換為二進位制表示:
typescript
function generateBinaryCode(threshold: number): string {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
let binaryCode = '';
for (let i = 0; i < data.length; i += 4) {
binaryCode += data[i] < threshold ? '1' : '0';
}
return binaryCode;
}