|
Author |
Topic: help with pixels[] array (Read 2727 times) |
|
mccutchen
|
help with pixels[] array
« on: Jan 7th, 2003, 8:04am » |
|
Can anyone tell me an easy way to figure out the index of a given pixel in the pixels[] array? If I want to modify the pixel at (300, 200), how do I figure out its index? It seems like there is a simple way to do this, but it's giving me a headache.
|
|
|
|
benelek
|
Re: help with pixels[] array
« Reply #1 on: Jan 7th, 2003, 8:18am » |
|
assuming the pixels in an array are indexed in the same indexNum=part-1 format as all other arrays, my guess is the following: in the top row, pixels would be 0,1,2,3,4, etc. the counting would continue on the next row, and following on horizontally. so if each row has 10 pixels, then the first pixel on the second row would be pixel number 11=1+10, with index number 10=11-1. SO, the pixel at (42,20) would have index number: (42 + 19*width) - 1; since the "42" is the number already counted in that row, and "19*width" represents the number of pixels in all the rows above. -jacob
|
« Last Edit: Jan 7th, 2003, 8:20am by benelek » |
|
|
|
|
fry
|
Re: help with pixels[] array
« Reply #2 on: Jan 7th, 2003, 3:11pm » |
|
it's even simpler.. to get a pixel out, it's: int index = y*width + x; or to go the other way: int x = index % width; int y = index / width; for those not familiar, the % is "modulo" which is the remainder of an integer division. very useful for this sort of thing. also, while on the subject of pixels and indices.. if you're messing with all the pixels in an array, you probably don't want to do the / and % or multiply by 'width' on every iteration in the loop. (this code is useful for video and image processing) this is a waste: Code:for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = y*width + x; // do something with index } } |
| a smarter version works like so: Code:int index = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // do something with index // just increment index index++; } } |
| because it's faster to just increment (index++) than to multiply (y*width) each time. especially when you move to other languages.
|
|
|
|
|