在OpenCV中复制像素值

时间:2015-10-05 17:20:46

标签: c++ opencv

我有RGB图像,例如大小为2x2如下:

[  0,  14, 255,  75, 156, 255;
  45, 255, 234, 236, 141, 255]

我想复制每个像素(所有RGB通道)2x2次,并获得如下图像:

[  0,  14, 255,  0, 14, 255,  75, 156, 255, 75, 156, 255;
   0,  14, 255,  0, 14, 255,  75, 156, 255, 75, 156, 255;
  45, 255, 234,  45, 255, 234, 236, 141, 255, 236, 141, 255;
  45, 255, 234,  45, 255, 234, 236, 141, 255, 236, 141, 255  ]

在Matlab或Python中,我只是通过使用kron函数来实现这一点,但我无法弄清楚如何在OpenCV C ++中轻松完成。请注意,这是一个简单的例子,我实际上想要将每个像素复制16x16并在更大的图像上复制,当然不是2x2。

3 个答案:

答案 0 :(得分:6)

您可以type使用最近邻插值resize

<强>代码:

INTER_NEAREST

<强>输出

Mat mInput(2, 2, CV_8UC3),mOutput(4, 4, CV_8UC3);

mInput.at<Vec3b>(0,0)= Vec3b(0,14,255);
mInput.at<Vec3b>(0,1)= Vec3b(75,156,255);
mInput.at<Vec3b>(1,0)= Vec3b(45,255,234);
mInput.at<Vec3b>(1,1)= Vec3b(236,141,255);

cout<<mInput<<"\n";

resize(mInput,mOutput,Size(4,4),0,0,INTER_NEAREST);

cout<<mOutput<<"\n";;    

感谢@wendelbsilva在评论中指出这一点。

答案 1 :(得分:0)

你可以包装kron函数,就像在Matlab和Python中那样。请注意,Kronecker产品是在单通道矩阵上定义的,因此您需要拆分平面BGR矩阵,应用kron,然后合并回来。

以下代码将生成您的确切输出:

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

Mat kron(const Mat A, const Mat B)
{
    CV_Assert(A.channels() == 1 && B.channels() == 1);

    Mat1d Ad, Bd;
    A.convertTo(Ad, CV_64F);
    B.convertTo(Bd, CV_64F);

    Mat1d Kd(Ad.rows * Bd.rows, Ad.cols * Bd.cols, 0.0);

    for (int ra = 0; ra < Ad.rows; ++ra)
    {
        for (int ca = 0; ca < Ad.cols; ++ca)
        {
            Kd(Range(ra*Bd.rows, (ra + 1)*Bd.rows), Range(ca*Bd.cols, (ca + 1)*Bd.cols)) = Bd.mul(Ad(ra, ca));
        }
    }
    Mat K;
    Kd.convertTo(K, A.type());
    return K;

}

int main()
{
    Mat3d A(2,2);
    A(0, 0) = Vec3d(0, 14, 255);
    A(0, 1) = Vec3d(75, 156, 255);
    A(1, 0) = Vec3d(45, 255, 234);
    A(1, 1) = Vec3d(236, 141, 255);

    cout << "A:" << endl;
    cout << A << endl;

    Mat1d B = Mat1d::ones(2,2);

    cout << "B:" << endl;
    cout << B << endl;

    vector<Mat> planes;
    split(A, planes);

    for (int i = 0; i < 3; ++i)
    {
        planes[i] = kron(planes[i], B);
    }

    Mat K;
    merge(planes, K);

    cout << "K:" << endl;
    cout << K << endl;


    return 0;
}

答案 2 :(得分:0)

我只使用OpenCV Repeat function,它比在最近的邻居中调整大小更快(并且更具可读性)。