32bit floodFill for ImageData of canvas


 /**
* floodFillOnImageData ImageData를 위한 floodFill. 32비트로 동작. 8비트보다 33%보다 빠르다!
* @param  {ImageData} imageData
* @param  {int} xf start x
* @param  {int} yf start y
* @param  {Array} colorset  [INT r, INT g, INT b, FLOAT alpha]
* @return {Boolean}           true:success , false:fail
*/
 function floodFillOnImageData(imageData,xf,yf,colorset){
var w = imageData.width;
var h = imageData.height;
if(xf < 0 || xf > w || yf < 0 ||yf > h){
console.error("wrong x,y");
return false;
}
if(isNaN(colorset[0])||isNaN(colorset[1])||isNaN(colorset[2])||isNaN(colorset[3]) || colorset[3] > 1){
console.error("wrong colorset");
return false;
}
let data32 = new Uint32Array(imageData.data.buffer);
let point ={x:xf,y:yf}
let x0 = w;
let y0 = h;
let colorData = [ colorset[0], colorset[1], colorset[2], colorset[3]*255 ];
let uint8bytes = Uint8Array.from(colorData);
let data32RGBA_rp = new Uint32Array(uint8bytes.buffer)[0];
let data32RGBA_sh = data32[(point.y*w+point.x)];
//-- 이미 같은 색으로 칠해져있다면 무시
if(data32RGBA_rp==data32RGBA_sh){
console.log("skip: start color is data32RGBA_rp==data32RGBA_sh");
return false;
}
let p1 = -1;
let stack = [];
let currPt = null;
let t32 = null;
let data32RGBA_cr = null;
stack.push(point);
while(stack.length > 0) {
currPt = stack.pop();
p1 = (currPt.y*w+currPt.x);
if(data32[p1] !== data32RGBA_sh){
continue;
}
data32[p1] = data32RGBA_rp
if(currPt.x < w-1) stack.push({x:currPt.x + 1, y:currPt.y}); // Fill the east neighbour
if(currPt.y < h-1) stack.push({x:currPt.x, y:currPt.y + 1}); // Fill the south neighbour
if(currPt.x > 0) stack.push({x:currPt.x - 1, y:currPt.y}); // Fill the west neighbour
if(currPt.y > 0) stack.push({x:currPt.x, y:currPt.y - 1}); // Fill the north neighbour
}
// imageData.data.set(data32.buffer);
return true;
}
imageData.data 는 Uint8ClampedArray 이다
imageData.data로 할 경우 FHD 크기 기준 1.4초 정도 걸린다.
Uint32Array 로 변환해서 처리할 경우 0.8초 정도 걸린다.

소스 체크해보니깐
arr[i] 를 하는데 시간이 꽤 많이 잡아 먹힌다.
32비트로 할 경우 그 단계가 1/4로 줄어든다.

댓글
  • No Nickname
    No Comment
  • 권한이 없습니다.
    {{m_row.m_nick}}
    -
목록형 📷 갤러리형
제목
[기본형] HTML (with 부트스트랩5.3 , jquery 3.7, vue.js)
유용한 리눅스(LINUX) 명령어
[공지] 기술 게시판
3.31
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.10
4.11
4.12
4.13
4.14
4.15
4.16
4.18
4.19
4.20
4.21
4.22
4.23
4.24
4.25
4.26
4.27
4.28
4.29
4.30
5.1
5.2
5.3
5.4