Iterate over a block of a 2D array by block in C ++

I am working on homework for an image reduction program in C ++. My photo is represented by a two-dimensional array of pixels; each pixel is an object with elements of "red", "green" and "blue". To solve the problem, I try to access a 2D array one block at a time, and then call a function that finds the average RGB value for each block and adds a new pixel to a smaller array of images. The size of each block (or scale factor) is entered by the user.

As an example, imagine a 2D array of 100 elements, for example myArray [10] [10]. If the user enters a compression ratio of 3, I will need to split the mini-2D arrays of size 3 by 3. I do not need to take into account overflow, so in this example I can ignore the last row and last column.

2D Array

I have most of the written program, including a function for finding the middle color. I am confused about how to navigate a 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 the small squares in the array.

Any help would be greatly appreciated!

+7
source share
3 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 - the entire width, block_width - the length of your blue squares in the diagram

+3
source

Here's how you go through 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 will leave figuring out how to quote through an array in different ways, as an exercise for the reader.

+3
source

you can use two nested loops for x and one for y and move the starting point of these loops over the image. Since this is homework, I did not set the code, but you should be able to process it.

0
source

All Articles