PhonoDots
PhonoDots

Reputation: 149

C++ cropping a contiguous 2D array

Let's say that I have an array called image which is a long contiguous array of "size" elements - as defined bellow. I'd like to crop this array (then getting a sub matrix) then, by modifying the sub array I'll automatically modify the source image (reference).

Be aware that the crop operation will return a non-contiguous array. This is in fact the problem.

Is there a way to do this elegantly in C++?

By the way, I'm not interested by using OpenCV, boost, etc...

thanks for your help.

template <class Type> class Image
{
private:
    Type *image;

public:

    int rows;
    int cols;
    int size;

    Image(int rows, int cols): rows(rows), cols(cols)
    {
        image = new Type[size = rows*cols];
    }
    ~Image()
    {
        delete [] image;
    }
    Type & at(int i, int j)
    {
        return image[cols*i + j];
    }
    void print()
    {
        for(int i = 0; i < rows; ++i)
        {
                for(int j = 0; j < cols; ++j)
                    cout << at(i,j) << " ";
                cout << endl;
        }
        cout << endl;

    }

}; 

Upvotes: 0

Views: 1525

Answers (1)

user1950929
user1950929

Reputation: 874

You can create a class CroppedImage that holds a reference or pointer to the original Image and offsets and provides its own methods, which add the offsets and then invoke the original images methods:

template <class Type> class CroppedImage
{
    private: 
        Image<Type> *original;
        int offsetX;
        int offsetY;
    public:
        int rows;
        int cols;
        int size;
        CroppedImage(Image<Type> *orig, int offX, int offY, int width, int height)
        {
            original = orig;
            offsetX = offX;
            offsetY = offY;
            rows = height;
            cols = width;
            size = rows*cols;
        }
        ~CroppedImage(){}
        Type & at(int i, int j)
        {

            return original->at(i+offsetX, j+offsetY);
        }
        void print()
        {
            for(int i = 0; i < rows; ++i)
            {
                    for(int j = 0; j < cols; ++j)
                        cout << at(i,j) << " ";
                    cout << endl;
            }
            cout << endl;
        }

}

I haven't tested it, there might be some typos and other errors. If you don't want to create a new class, you can incorporate the code into your Image class.

Upvotes: 3

Related Questions