kelly
kelly

Reputation: 139

Iterate through 2D Array block by block in C++

I'm working on a homework assignment for an image shrinking program in C++. My picture is represented by a 2D array of pixels; each pixel is an object with members "red", "green" and "blue." To solve the problem I am trying to access the 2D array one block at a time and then call a function which finds the average RGB value of each block and adds a new pixel to a smaller image array. The size of each block (or scale factor) is input by the user.

As an example, imagine a 100-item 2D array like myArray[10][10]. If the user input a shrink factor of 3, I would need to break out mini 2D arrays of size 3 by 3. I do not have to account for overflow, so in this example I can ignore the last row and the last column.

2D Array

I have most of the program written, including the function to find the average color. I am confused about how to traverse the 2D array. I know how to cycle through a 2D array sequentially (one row at a time), but I'm not sure how to get little squares within an array.

Any help would be greatly appreciated!

Upvotes: 7

Views: 4083

Answers (3)

Pubby
Pubby

Reputation: 53017

Something like this should work:

for(size_t bx = 0; bx < width;  bx += block_width)
for(size_t by = 0; by < height; by += block_height) {
  float sum = 0;
  for(size_t x = 0; x < block_width; ++x)
  for(size_t y = 0; y < block_height; ++y) {
    sum += array[bx + x][by + y];
  }
  average = sum / (block_width * block_height);
  new_array[bx][by] = average;
}

width is the whole width, block_width is the length of your blue squares on diagram

Upvotes: 4

David Titarenco
David Titarenco

Reputation: 33386

This is how you traverse an array in C++:

for(i=0; i < m; i++) {
  for(j=0; j < n; j++) {
    // do something with myArray[i][j] where i represents the row and j the column
  }
}

I'll leave figuring out how to cylcle through the array in different ways as an exercise to the reader.

Upvotes: 3

smitec
smitec

Reputation: 3049

you could use two nested loops one for x and one for y and move the start point of those loops across the image. As this is homework I wont put any code up but you should be able to work it out.

Upvotes: 0

Related Questions