开发者

Efficiently editing Pixels in an Image

开发者 https://www.devze.com 2023-02-14 19:12 出处:网络
I have an 8bit Image (stored in an Array) containing black(0) and white(255) pixels. Say I want to change all Bla开发者_如何学Cck pixels in the image to grey(say 120) pixels. What is the fastest way I

I have an 8bit Image (stored in an Array) containing black(0) and white(255) pixels. Say I want to change all Bla开发者_如何学Cck 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消