影像處理在現代網頁應用中扮演著重要角色,常用於影像分析和使用者互動。本文將使用 JavaScript 和 HTML5 Canvas 實現一些基本的影像處理操作,包括灰度轉換、去除邊框、提取有效區域和影像分割。
環境準備
首先,確保你有一個基本的 HTML 檔案,其中包含一個 Canvas 元素。以下是示例結構:
html
載入影像
首先,實現影像上傳並繪製到 Canvas 上:
javascript
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
const upload = document.getElementById('upload');
upload.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
});
灰度轉換
灰度轉換是影像處理中最常用的操作,以下函式將影像轉換為灰度:
javascript
function convertToGray() {
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);
}
去除影像邊框
去除邊框可以將影像的邊界部分設定為白色:
javascript
function clearBorders(borderWidth) {
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);
}
提取有效區域
提取有效區域的過程是遍歷影像,找到主要內容區域,以下是相應程式碼:
javascript
function getValidRegion(threshold) {
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);
}
影像分割
影像分割將影像按行列切分為多個小塊,以下程式碼實現這一功能:
javascript
function splitImage(rows, cols) {
const width = canvas.width / cols;
const height = canvas.height / rows;
const images = [];
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;
}
生成二進位制編碼
生成二進位制編碼串,可以將影像中的灰度值轉換為二進位制表示:
javascript
function generateBinaryCode(threshold) {
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;
}