## 码农干货系列【4】--图像识别之矩形区域搜索

2012-07-23 07:37  【当耐特】  阅读(8576)  评论(32编辑  收藏

# 应用场景

1.精灵编辑器或者css sprites辅助工具（当我们需要逆着TexturePacker行事的时候），如下图所示：

2.手写识别输入

3.魔法画板程序

# 矩形区域识别

    var increasePixel = 1, leftIncreasePixel = 2, rightIncreasePixel = 2, upIncreasePixel = 2, downIncreasePixel = 2;    function searchTransparentRectByTargetPoint(p) {        var p1 = { x: p.x - leftIncreasePixel, y: p.y - upIncreasePixel };        var p2 = { x: p.x + rightIncreasePixel, y: p.y - upIncreasePixel };        var p3 = { x: p.x + rightIncreasePixel, y: p.y + downIncreasePixel };        var p4 = { x: p.x - leftIncreasePixel, y: p.y + downIncreasePixel };        var breakTag = true;        if (!isXLineTransparent(p1, p2)) {            upIncreasePixel += increasePixel;            breakTag = false;        }        if (!isYLineTransparent(p2, p3)) {            breakTag = false;            rightIncreasePixel += increasePixel;        }        if (!isXLineTransparent(p4, p3)) {            breakTag = false;            downIncreasePixel += increasePixel;        }        if (!isYLineTransparent(p1, p4)) {            breakTag = false;            leftIncreasePixel += increasePixel;        }        if (breakTag) {            return [p1.x, p1.y, p3.x - p1.x, p3.y - p1.y];        } else {            return searchTransparentRectByCenterPoint(p);        }    }

    function isXLineTransparent(p1, p2) {        var _y = p2.y;        for (var i = p1.x; i < p2.x + 1; i++) {            var startIndex = this.getImageDataStartIndexByPosition({ x: i, y: _y });            var totalPixel = this.imageData.data[startIndex] + this.imageData.data[startIndex + 1] + this.imageData.data[startIndex + 2] + this.imageData.data[startIndex + 3];            if (totalPixel !== 0) {                return false;            }        }        return true;    }    function isYLineTransparent(p1, p2) {        var _x = p2.x;        for (var i = p1.y; i < p2.y + 1; i++) {            var startIndex = this.getImageDataStartIndexByPosition({ x: _x, y: i });            var totalPixel = this.imageData.data[startIndex] + this.imageData.data[startIndex + 1] + this.imageData.data[startIndex + 2] + this.imageData.data[startIndex + 3];            if (totalPixel !== 0) {                return false;            }        }        return true;    }