如何在opencv4node.js中将某个RGB值的所有像素替换为另一个值

问题描述

我为此使用了opencv4nodejs和nodejs,

我正在尝试获取图像RGB值并替换特定索引中的特定RGB值并创建2d数组。

const color_map = [[255,255,0],[255,[0,255],0]];

const input_image = cv.imread("Data/IMG/train_labels/0.png");

let index = 0

function form_2D_label(mat) {
    const image = mat.cvtColor(cv.COLOR_BGR2RGB);
    const imageBuffer = mat.getData();
    const ui8 = new Uint8Array(imageBuffer);

    const imageData = new Array((image.rows * image.cols))

    for (let i = 0; i < ui8.length; i += 3) {
        imageData[index] = [ui8[i],ui8[i + 1],ui8[i + 2]];
        for (const [index,element] of color_map.entries()) { // enumerate color map
             // console.log(index,element);
             // I am trying todo if imageData[index] value = [255,0] as 0,if [255,0] as 1,if [0,255] as 2 like this..
        }

        console.log(imageData[index]) // [255,0] / [255,0] like this
        index++;
    }

    return imageData;

}

const test = form_2D_label(input_image);
console.log(test);

当前输出

[
[ 0,0 ],[ 255,[ 0,0]
]

预期一个

[
[ 4,1,4,0 ]
]

解决方法

您的问题有一些问题。

首先color_map仅包含5个元素,但是预期结果的索引范围是0到5(6个元素),我认为这是一个错误,您只需要真实的索引即可。

在代码中所有其他地方中,第二个是分配的值index,所以我只假设它是下一个可用的索引,而改用push属性。

由于您实际上并不希望返回多维数组,而只想返回索引的二维数组,因此返回imageData毫无意义。

授予您在注释部分中说明的条件,即只有色图值才是您可以尝试做的事情:

const color_map = [[255,255,0],[255,[0,255],0]];

function form_2D_label(mat) {
    const image = mat.cvtColor(cv.COLOR_BGR2RGB);
    const imageBuffer = mat.getData();
    const ui8 = new Uint8Array(imageBuffer);

    const imageData = [];

    for (let i = 0; i < ui8.length; i += 3) {
        imageData.push([ui8[i],ui8[i + 1],ui8[i + 2]]);
        console.log(imageData[imageData.length - 1])
    }

    return [imageData.map(el => color_map.findIndex(color => arrayEquals(color,el)))];
}

function arrayEquals(array1,array2) {
    for (let i = 0,l = array2.length; i < l; i++) {
        if (array2[i] !== array1[i]) return false;
    }
    return true;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...