【问题标题】:OpenCV convert color per pixelOpenCV每像素转换颜色
【发布时间】:2015-08-09 17:01:07
【问题描述】:

您好,我想转换图像中的颜色,我使用的是逐像素方法,但它似乎很慢

src.getPixels(pixels, 0, width, 0, 0, width, height);

        // RGB values
        int R;

        for (int i = 0; i < pixels.length; i++) {
            // Get RGB values as ints


            // Set pixel color
            pixels[i] = color;

        }

        // Set pixels
        src.setPixels(pixels, 0, width, 0, 0, width, height);

我的问题,我有什么办法可以使用 openCV 做到这一点?将像素更改为我想要的颜色?

【问题讨论】:

  • 你想用一种颜色填充整个图像还是每个像素都有不同的颜色?
  • 谢谢,每个像素都不应该有不同的颜色

标签: android opencv image-processing colors pixel


【解决方案1】:

我建议this excellent article 了解如何访问/修改 opencv 图像缓冲区。我建议 “有效的方式”:

 int i,j;
    uchar* p;
    for( i = 0; i < nRows; ++i)
    {
        p = I.ptr<uchar>(i);
        for ( j = 0; j < nCols; ++j)
        {
            p[j] = table[p[j]];
        }

或“迭代器安全方法”:

MatIterator_<Vec3b> it, end;
for( it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)
{
   (*it)[0] = table[(*it)[0]];
   (*it)[1] = table[(*it)[1]];
   (*it)[2] = table[(*it)[2]];
}

为了进一步优化,使用cv::LUT()(在可能的情况下)可以大大提高速度,但设计/编码更加密集。

【讨论】:

  • 感谢您的链接,但是,您能否将信息直接添加到此答案中?链接往往会随着时间的推移而中断,然后这个答案就不再有用了。
【解决方案2】:

您可以通过以下方式访问像素:

img.at<Type>(y, x);

所以要更改一个 RGB 值,您可以使用:

// read color
Vec3b intensity = img.at<Vec3b>(y, x);

// compute new color using intensity.val[0] etc. to access color values

// write new color
img.at<Vec3b>(y, x) = intensity;

@Boyko 提到了来自 OpenCV 的Article,如果您想遍历所有像素,则可以快速访问图像像素。本文中我更喜欢的方法是迭代器方法,因为它只比直接指针访问慢一点,但使用起来更安全。

示例代码:

Mat& AssignNewColors(Mat& img)
{
    // accept only char type matrices
    CV_Assert(img.depth() != sizeof(uchar));

    const int channels = img.channels();
    switch(channels)
    {
    // case 1: skipped here
    case 3:
        {
         // Read RGG Pixels
         Mat_<Vec3b> _img = img;

         for( int i = 0; i < img.rows; ++i)
            for( int j = 0; j < img.cols; ++j )
               {
                   _img(i,j)[0] = computeNewColor(_img(i,j)[0]);
                   _img(i,j)[1] = computeNewColor(_img(i,j)[1]);
                   _img(i,j)[2] = computeNewColor(_img(i,j)[2]);
            }
         img = _img;
         break;
        }
    }

    return img;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多