• 颜色分类函数


    逻辑原理:

    1、找出图片种最多的一种颜色,将它的相似颜色和它分类成0;

    2、找出剩下的颜色种的最多一种颜色,将它的相似颜色和它分类成1;

    3、找出剩下的颜色种的最多一种颜色,将它的相似颜色和它分类成2;

    如果类别限制为maxTagNum,将剩下的颜色都分类成maxTagNum


    const getPixels = require("get-pixels")
    function getPixelsSync(filename){
    return new Promise(function (resolve,reject) {
    getPixels(filename, function(err, pixels) {
    if(err) {
    console.log("Bad image path")
    reject(err)
    return
    }
    resolve(pixels)
    })
    })
    }
    const {Matrix,Fraction,Point,Line} = require("./utils/math");
    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]))<75){
    return 1;
    }
    return 0;
    }
    //将颜色分成多少种 maxTagNum是限制最大多少种
    function sortMatColor(mat1,maxTagNum){

    function sortColor(num) {
    let map={}
    let maxKey;
    mat1.rowEach(function (item,r,c) {
    if(typeof item==="number"){return;}
    const key=item.join(',')
    if(map[key]===undefined){
    map[key]=0;
    }
    map[key]++;
    if(!maxKey){
    maxKey=key;
    }else if(map[maxKey]<map[key]){
    maxKey=key;
    }
    })

    let bgColor=maxKey.split(',').map((item)=>parseInt(item));

    let running=false;
    mat1.rowMap(function (item,r,c) {
    if(typeof item==="number"){return item;}
    if(maxTagNum-1<=num||isNearColor(item,bgColor)){
    return num;
    }else{
    running=true;
    return item;
    }
    })
    if(running){
    return sortColor(num+1);
    }
    return num+1;
    }
    return sortColor(0);
    }

    async function init() {
    const pixels=await getPixelsSync('1.jpg');
    console.log(pixels)
    const [w,h]=pixels.shape;

    //1定义矩阵
    const mat1=new Matrix([],h,w);
    mat1.rowMap(function (item,r,c) {
    return getColor(c,r,pixels);
    })
    console.log(sortMatColor(mat1,3))
    //生产0、1、2种颜色类别
    console.log(mat1.toString())
    }
    init()

    // scanRound(0,0,100,100,function (x,y) {
    // return 1;
    // },function (x,y) {
    // console.log(x,y);
    // })
  • 相关阅读:
    bzoj 4245: [ONTAK2015]OR-XOR【按位贪心】
    bzoj 4247: 挂饰【dp】
    bzoj 3503: [Cqoi2014]和谐矩阵【高斯消元】
    bzoj 3029: 守卫者的挑战【概率dp】
    bzoj 3732: Network【克鲁斯卡尔+树链剖分】
    bzoj 1040: [ZJOI2008]骑士【基环树+树形dp】
    bzoj 3668: [Noi2014]起床困难综合症【贪心】
    bzoj 2157: 旅游【树链剖分+线段树】
    bzoj 4521: [Cqoi2016]手机号码【数位dp】
    bzoj 3437: 小P的牧场【斜率优化】
  • 原文地址:https://www.cnblogs.com/caoke/p/11097220.html
Copyright © 2020-2023  润新知