efficient cropping calculation in processing -
i loading png in processing. png has lot of unused pixels around actual image. luckily pixels transparent. goal crop png show image , rid of unused pixels. first step calculate bounds of image. wanted check every pixel alpha value , see if pixel highest or lowest coordinate bounds. this:
------ ------ --->oo oooooo oooooo
then realized needed until first non-alpha pixel , repeat backwards highest coordinate bound. this:
------ -->ooo oooooo ooo<-- ------
this mean less calculating same result. code got out of still seems complex. here is:
class rect { //class storing boundries int xmin, xmax, ymin, ymax; rect() { } } pimage gfx; void setup() { size(800, 600); gfx = loadimage("resources/test.png"); rect _bounds = calcbounds(); //first calculate boundries cropimage(_bounds); //then crop image using boundries } void draw() { } rect calcbounds() { rect _bounds = new rect(); boolean _coordfound = false; gfx.loadpixels(); //x min bounds (int = 0; < gfx.width; i++) { //rows (int i2 = 0; i2 < gfx.height; i2++) { //columns if (alpha(gfx.pixels[(gfx.width * i2) + i]) != 0) { _bounds.xmin = i; _coordfound = true; break; } } if (_coordfound) { break; } } //x max bounds _coordfound = false; (int = gfx.width - 1; >= 0; i--) { //rows (int i2 = gfx.height - 1; i2 >= 0; i2--) { //columns if (alpha(gfx.pixels[(gfx.width * i2) + i]) != 0) { _bounds.xmax = i; _coordfound = true; break; } } if (_coordfound) { break; } } //y min bounds _coordfound = false; (int = 0; < gfx.height; i++) { //columns (int i2 = 0; i2 < gfx.width; i2++) { //rows if (alpha(gfx.pixels[(gfx.width * i) + i2]) != 0) { _bounds.ymin = i; _coordfound = true; break; } } if (_coordfound) { break; } } //y max bounds _coordfound = false; (int = gfx.height - 1; >= 0; i--) { //columns (int i2 = gfx.width -1; i2 >= 0; i2--) { //rows if (alpha(gfx.pixels[(gfx.width * i) + i2]) != 0) { _bounds.ymax = i; _coordfound = true; break; } } if (_coordfound) { break; } } return _bounds; } void cropimage(rect _bounds) { pimage _temp = createimage((_bounds.xmax - _bounds.xmin) + 1, (_bounds.ymax - _bounds.ymin) + 1, argb); _temp.copy(gfx, _bounds.xmin, _bounds.ymin, (_bounds.xmax - _bounds.xmin) + 1, (_bounds.ymax - _bounds.ymin)+ 1, 0, 0, _temp.width, _temp.height); gfx = _temp; //now image cropped }
isnt there more efficient/faster way calculate bounds of image? , still want boundries coordinates afterward instead of cutting away @ image during calculation.
if store last empty line found e.g. horizontal minimum , maximum scan in variable, can use constrain vertical scanning area has not yet been checked being empty, instead of having scan full columns. depending on amount , shape of croppable area can save quite bit - see schematic visual explanation of modified algorithm:
by way, in //x min bounds
scan seem iterating on width in both for
loops, should height in 1 though? (unless images square of course :))
Comments
Post a Comment