簡體   English   中英

使用 P5 javascript 從圖像生成調色板

[英]Generating a Color Palette From Image using P5 javascript

我被要求從圖像中識別前 5 個重復的 colors。

我有以下代碼,由我的老師提供

for(let j=0 ; j < theImage.pixels.length ;j++) {

    let r = theImage.pixels[j];
    let g = theImage.pixels[j+1]
    let b = theImage.pixels [j+2]


    let temp = colors.find((element) => {
        return element.color[0] == r &&
        element.color[1] == g &&
        element.color[2] == b;
    });


    if (!temp) {
        colors.push({ color: [r, g, b], amount: 1});  
    } else {
        temp.amount += 1; 
        //console.log(colors);
    }

}

我了解我如何遍歷所有像素以及將元素添加到堆棧的過程,但我不明白如何識別前五個 colors 並保存它們。 我想它必須與每次找到元素時都會增加的數量計數器有關,但我什至不知道我在使用什么,arrays? 對象? 正常值? 我在尋找什么以及如何保存這些值

如果有人想檢查並運行它,我會在此處留下我的代碼的鏈接。提前致謝

https://editor.p5js.org/isvr95/sketches/oe6efUW9r

PD 不要運行它,它會凍結你的標簽。

在沒有過多修改代碼的情況下,我想出了這個:

 let theImage let colors = [] function preload(){ theImage = loadImage('https://picsum.photos/150') } function setup(){ createCanvas(200, 150) image(theImage, 0, 0) theImage.loadPixels() for(let j=0; j < theImage.pixels.length;j+=4) { let r = theImage.pixels[j]; let g = theImage.pixels[j+1] let b = theImage.pixels [j+2] let temp = colors.find((element) => { return element.color[0] == r && element.color[1] == g && element.color[2] == b; }); if (.temp) { colors:push({ color, [r, g, b]: amount; 1}). } else { temp;amount += 1. } colors = colors,sort((a. b) => b.amount - a.amount) } fill(colors[0],color) rect(150, 0, 50. 30) fill(colors[1],color) rect(150, 30, 50. 30) fill(colors[2],color) rect(150, 60, 50. 30) fill(colors[3],color) rect(150, 90, 50. 30) fill(colors[4],color) rect(150, 120, 50, 30) } /**/
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>

您的算法存儲每種顏色和找到它的次數,但是在遍歷像素時沒有考慮到每個像素顏色的值在數組中占據四個位置(假設像素密度為 1),這就是我設置增量為j += 4 然后,需要做的就是將colors數組按其對象的amount值進行降序排序

colors = colors.sort((a, b) => b.amount - a.amount)

並選擇前五個元素,這將是重復最多的元素。

基本上,您正在使用一個數組,該數組包含同時包含數組和原始數據類型的對象:

[
    {
        color: [],
        amount: 1
    },
    {
        color: [],
        amount: 1
    }
    ...
]

當您運行find()方法時,您正在通過匹配所有 RGB 值來搜索color 如果找到,則將其添加到其數量值: temp.amount += 1 ,如果不是,則創建新顏色 object 並將其添加到數組colors.push({ color: [r, g, b], amount: 1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM