其他分享
首页 > 其他分享> > 判断图像中有多少行文本(开发中)

判断图像中有多少行文本(开发中)

作者:互联网

const fs = require("fs")
const getPixels = require("get-pixels")
function getColor(x,y,pixels) {
    return [
        pixels.data[x*4+y*4*pixels.shape[0]],
        pixels.data[x*4+1+y*4*pixels.shape[0]],
        pixels.data[x*4+2+y*4*pixels.shape[0]],
        pixels.data[x*4+3+y*4*pixels.shape[0]]
    ]
}
function isNearColor(color1,color2){
    if((Math.abs(color1[0]-color2[0])+Math.abs(color1[1]-color2[1])+Math.abs(color1[2]-color2[2])+Math.abs(color1[3]-color2[3]))<40){
        return 1;
    }
    return 0;
}
getPixels("1.jpg", function(err, pixels) {
    if(err) {
        console.log("Bad image path")
        return
    }
    scanLine(pixels.shape[0],pixels.shape[1],function (curp,prep) {
        return isNearColor(getColor(curp.x,curp.y,pixels),getColor(prep.x,prep.y,pixels))
    },function (){},pixels)

})


//行扫描函数 line
function scanLine(w,h,isOpenFunc,callfunc,pixels) {
    const map={}
    function isOpen(curp,prep) {
            const {x,y}=curp;
        if(map[x+','+y]){
            return 0
        }
        if(x<0||x>=w||y<0||y>=h){
            return 0;
        }
        return isOpenFunc(curp,prep)
    }
    function callback(x,y) {
        map[x+','+y]=true;
        return callfunc(x,y)
    }
    let xline=[];
    let yline=[];
    function isXLine(x,y){
        return  y===0||xline.indexOf(`${x},${y}`)>-1
    }
    function isYLine(x,y){
        return  x===w-1||yline.indexOf(`${x},${y}`)>-1
    }

    for(let i=0;i<h;i++){
        yline.push(`0,${i}`);
    }
    let index=0;
    const posArr=[]
    let state='end';
    while(index<yline.length){

        //发出x射线
        let [x,y]=yline[index].split(',');
        x=parseInt(x);
        y=parseInt(y);
        //state

        const arr=[];
        while(isOpen({x:x+1,y},{x,y})){
            x=x+1;
            arr.push({x,y})
        }

        if(x+1==w){
            if(state!=='end'){
                console.log(yline[index])
            }
            state='end'
        }else{
            if(state!=='break'){
                console.log(yline[index])
            }
            state='break'
        }

        index++;
    }
}

// scanRound(0,0,100,100,function (x,y) {
//     return 1;
// },function (x,y) {
//     console.log(x,y);
// })

 

https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561552141135&di=170679fcee4e69499f94b5167c8e474a&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201208%2F27%2F20120827144059_sijxK.jpeg

标签:function,return,中有,color1,shape,color2,图像,文本,pixels
来源: https://www.cnblogs.com/caoke/p/11093099.html