我们如何为使用 YOLO 检测到的不同对象设置不同的“颜色”

How can we set different `colors` for different objects detected using YOLO

我们如何为使用 YOLO 检测到的不同对象设置不同的 colors。现在检测到的所有内容都显示在绿色矩形中。

function draw() {
    image(video, 0, 0, width, height); // Displaying image on a canvas
    for (let i = 0; i < objects.length; i++)  //Iterating through all objects
    {
        noStroke();
        fill(0, 255, 0); //Color of text
        text(objects[i].label, objects[i].x * width, objects[i].y * height - 5); 
        //Displaying the label
        noFill();
        strokeWeight(4); 
        stroke(0, 255, 0); //Defining stroke for rectangular outline
        rect(objects[i].x * width, objects[i].y * height, objects[i].w * width, 
        objects[i].h * height);
    }
}

stroke() 设置全局状态,它设置用于在形状周围绘制线条和边框的颜色。这种状态甚至超出帧。
这意味着在调用 stroke() 之后绘制的所有对象都使用设置的颜色绘制。
如果你想改变颜色,你必须再次调用 stroke()

如果您想使用不同的颜色,您可以定义颜色列表并使用 modulo operator (%) 获取颜色列表的索引。例如使用红色、绿色和蓝色:

colorList = [[255, 0, 0], [0, 255, 0], [0, 0, 255]];

function draw() {

    // [...]


    for (let i = 0; i < objects.length; i++) {

        // [...]

        let colorI = i % colorList.length;
        stroke(...colorList[colorI]);

        // [...]
    }
}