颜色分类函数

逻辑原理:

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);
// })

 

转载于:https://www.cnblogs.com/caoke/p/11097220.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值