아래는 자바스크립트 (JavaScript) 와 HTML Canvas API 를 이용해 이미지를 로드하고, 말씀하신 방식으로 2x3 영역으로 나누어 중심 30% 영역의 평균 색상을 추출하는 코드입니다.
⸻
전체 코드 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Extractor</title>
</head>
<body>
<input type="file" id="imageInput" accept="image/*" />
<canvas id="canvas" style="display:none;"></canvas>
<script>
document.getElementById('imageInput').addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) return;
const img = new Image();
img.onload = () => processImage(img);
img.src = URL.createObjectURL(file);
});
function processImage(img) {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 원본 이미지 크기 기준
const originalWidth = img.width;
const originalHeight = img.height;
// 가로 90%, 세로 60% 영역만 사용
const roiWidth = Math.floor(originalWidth * 0.9);
const roiHeight = Math.floor(originalHeight * 0.6);
canvas.width = roiWidth;
canvas.height = roiHeight;
// 캔버스에 이미지 일부만 그리기
ctx.drawImage(img, 0, 0, roiWidth, roiHeight);
const colors = [];
const rows = 2;
const cols = 3;
const blockWidth = roiWidth / cols;
const blockHeight = roiHeight / rows;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
// 블록 중심 좌표
const centerX = Math.floor((col + 0.5) * blockWidth);
const centerY = Math.floor((row + 0.5) * blockHeight);
// 중심 30% 영역 크기
const regionWidth = Math.floor(blockWidth * 0.3);
const regionHeight = Math.floor(blockHeight * 0.3);
const startX = Math.floor(centerX - regionWidth / 2);
const startY = Math.floor(centerY - regionHeight / 2);
const imageData = ctx.getImageData(startX, startY, regionWidth, regionHeight);
const data = imageData.data;
let r = 0, g = 0, b = 0;
const totalPixels = regionWidth * regionHeight;
for (let i = 0; i < data.length; i += 4) {
r += data[i]; // R
g += data[i + 1]; // G
b += data[i + 2]; // B
}
r = Math.round(r / totalPixels);
g = Math.round(g / totalPixels);
b = Math.round(b / totalPixels);
colors.push({ r, g, b });
}
}
console.log("Extracted Colors:", colors);
}
</script>
</body>
</html>
⸻
주요 포인트 정리:
• <input type="file"> 를 사용해 이미지 업로드
• 캔버스에서 이미지의 좌측 상단 90% x 60% 영역만 그림
• 그 영역을 2x3 블록으로 나눈 후 각 블록의 중심 30% 영역 추출
• 해당 중심 부분의 픽셀 색상 평균(RGB) 계산
⸻
예시 출력:
Extracted Colors: [
{ r: 255, g: 0, b: 0 }, // 빨강
{ r: 0, g: 255, b: 0 }, // 초록
{ r: 0, g: 0, b: 255 }, // 파랑
{ r: 255, g: 255, b: 0 }, // 노랑
{ r: 255, g: 255, b: 255 }, // 흰색
{ r: 0, g: 0, b: 0 } // 검정
]
⸻
필요하시면:
• 색 이름 추정,
• 각 블록에 박스나 색상 오버레이 표시,
• 웹캠 실시간 색 추출 등도 추가해 드릴 수 있습니다.
원하시면 말씀해주세요!
카테고리 없음
댓글