微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。