简体   繁体   中英

Image Editor and Vector dimensions C++

I'm working on a basic image editor using vectors and I'm trying to get a matrix like the one shown below, a 4 by 4 but with each slot containing 3 values (RGB values)

 0  0  0    100 0  0      0  0  0    255   0 255
 0  0  0    0 255 175     0  0  0     0    0  0
 0  0  0    0  0  0       0 15 175    0    0  0
 255 0 255  0  0  0       0  0  0    255  255 255

So far I've been able to get a matrix put in with this code (I think..)

int rows;
int columns;
fin >> rows;
fin >> columns;
vector<vector<int> > image_dimensions(rows);
for (int i = 0; i < rows; i++)
    image_dimensions[i].resize(columns);

This is only to create a matrix full of 0s. How can I make each slot contain three RGB values like the example showed? Finally, what complicated loop would I have to use to be able to change the individual values in each slot, like turning 0 0 0 into 155 0 255 for example?

At the moment you use the primitive integer type. Consider to store some more complex like a RGB class:

class RGB {
private:
   std::unit8_t r, g, b;
public:
   RGB() {}
   RGB(int r, int g, int b) : r(r), g(g), b(b){ }
}

You can simple construct objects with:

rgb = RGB(255,255,255);

After that you can store the objects in your vector.

int rows;
int columns;
fin >> rows;
fin >> columns;
vector<vector<RGB> > image_dimensions(rows);
for (int i = 0; i < rows; i++)
   image_dimensions[i].resize(columns);

The difference to your example is, that the vector can store objects from the class RGB. If you like you can now iterate through the vector:

for (int i = 0; i < columns; i++)
   for (int i = 0; i < rows; i++)
       image_dimensions[i][j] = RGB(0,0,0);

edit: based on the comment, it is probably better to not waste space and use the the uint8 type. So there is no more need for the verification. And you could use a flat vector and calculate the 2d index. If you work with big matrices this will be generate a more efficient solution.

edit2: A second possible solution without creating a new class is to use the std tuple class:

std::tuple<std::unit8_t, std::unit8_t, std::unit8_t > rgb(0,0,0);

In this case your vector have to store this kind of tuple. More tuple informations: klick

By the way: creating a little class or structure should not disturb you. ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM