Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 253
kelly Avatar asked Dec 08 '11 00:12

kelly


1 Answers

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

like image 104
Pubby Avatar answered Oct 06 '22 17:10

Pubby