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

我为此使用了 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 = 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, 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 ]

]


梵蒂冈之花
浏览 159回答 1
1回答

慕尼黑5688855

你的问题有几个问题。首先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) {&nbsp; &nbsp; const image = mat.cvtColor(cv.COLOR_BGR2RGB);&nbsp; &nbsp; const imageBuffer = mat.getData();&nbsp; &nbsp; const ui8 = new Uint8Array(imageBuffer);&nbsp; &nbsp; const imageData = [];&nbsp; &nbsp; for (let i = 0; i < ui8.length; i += 3) {&nbsp; &nbsp; &nbsp; &nbsp; imageData.push([ui8[i], ui8[i + 1], ui8[i + 2]]);&nbsp; &nbsp; &nbsp; &nbsp; console.log(imageData[imageData.length - 1])&nbsp; &nbsp; }&nbsp; &nbsp; return [imageData.map(el => color_map.findIndex(color => arrayEquals(color, el)))];}function arrayEquals(array1, array2) {&nbsp; &nbsp; for (let i = 0, l = array2.length; i < l; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (array2[i] !== array1[i]) return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript