【问题标题】:How to replace all pixels of a certain RGB value with another value in opencv4nodejs如何用opencv4nodejs中的另一个值替换某个RGB值的所有像素
【发布时间】:2020-08-14 10:02:56
【问题描述】:

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

【问题讨论】:

  • color_map 只有这么多值,如果两个元素都不匹配,预期的行为是什么?
  • 输入图像具有所有五个颜色图值...我只给出当前输出的一些示例...如果当前输出像这样预期的输出将高于输出...

标签: javascript node.js image-processing opencv4nodejs


【解决方案1】:

您的问题有一些问题。

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

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

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

授予您在 cmets 部分中解释的条件,即颜色映射值将是您可以尝试做的唯一事情:

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;
}

【讨论】:

  • 感谢您的友好回复,现在我修复了我的代码
猜你喜欢
  • 2020-05-18
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 2018-01-26
相关资源
最近更新 更多