简体   繁体   中英

Efficiently editing Pixels in an Image

I have an 8bit Image (stored in an Array) containing black(0) and white(255) pixels. Say I want to change all Black pixels in the image to grey(say 120) pixels. What is the fastest way I can change Black to Grey.

I thought of two approaches-

  1. Start checking every single pixel in the image. As soon as a black pixel is found change it to grey. Continue till end of image. (Slower but easier)

  2. Start checking pixels. When a black pixel is found maintain a counter to track it. Continue incrementing the counter till the next white pixel. Then goto the counter and use a fast function like memset to change a group of black pixels to grey. (Not sure but I think this may be faster)

I have a huge 1GB image therefore approach 1 is pretty slow. Is there a better(faster) way to change/edit pixels?

Probably quicker to do it a word at a time (using word aligned accesses).

You can just bitwise OR with 0x78787878 (assuming 32 bits). This will not affect white pixels but will set black pixels to the required value.

I think the problem with the first approach is that you read and write the same 32/64/x bits (depending on memory architecture/bus width) muliple times. It should be faster if you read and write the bits corresponding to the bus width once.

In the following snippet, getPixelsSizeOfLong returns the bites according to the width of the bus (say 4 bytes) and there reduces transfering bits between cache and cpu.

// Forward declaration:
unsigned long getPixelsSizeOfLong(byteInImage unsigned int);
void          setPixelsSizeOfLong(byteInImage unsigned int, newBitValue unsigned long);

unsinged long l;

for (a=0; a+=sizeof(l); a<nof_pixels) {
  l  = getPixelsSizeOfLong(a);
  l |= 120;
  setPixelsSizeOfLong(a, l);
}

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