为了账号安全,请及时绑定邮箱和手机立即绑定

如何用opencv4nodejs中的另一个值替换某个RGB值的所有像素

如何用opencv4nodejs中的另一个值替换某个RGB值的所有像素

梵蒂冈之花 2023-01-06 09:46:54
我为此使用了 opencv4nodejs 和 nodejs,我正在尝试获取图像 RGB 值并替换特定索引中的特定 RGB 值并创建一个二维数组。const color_map = [[255,255,0], [255,0,0], [0,255,255], [0,255,0], [0,0,0]];const input_image = cv.imread("Data/IMG/train_labels/0.png");let index = 0function 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, 255, 0] as 0, if [255, 0, 0] as 1, if [0, 255, 255] as 2 like this..        }        console.log(imageData[index]) // [255, 255, 0] / [255, 0, 0] like this        index++;    }    return imageData;}const test = form_2D_label(input_image);console.log(test);电流输出[[ 0, 0, 0 ], [ 255, 0, 0 ], [ 0, 0, 0 ], [ 255, 0, 0 ], [ 0, 0, 0 ],[255, 255, 0]]预期的一个[[ 4, 1, 4, 1, 4, 0 ]]
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

你的问题有几个问题。


首先color_map只有 5 个元素,但预期结果的索引从 0 到 5(6 个元素),我认为这是一个错误,你只需要真正的索引。


其次,您的代码中没有index分配的值,所以我假设它是下一个可用索引,并改用push属性。


由于您实际上不想返回多维数组,而只想返回二维索引数组,因此返回imageData.


考虑到您在评论部分解释的条件,即颜色映射值将是您唯一可以尝试做的事情:


const color_map = [[255,255,0], [255,0,0], [0,255,255], [0,255,0], [0,0,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;

}


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 158 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号