問題描述
在 C++ 中查找像素 RGB 數據的最快方法是什麼? (What is the fastest method to lookup pixel RGB data in C++?)
我想查看 100 X 100 正方形屏幕中每個像素的 RGB 數據並將其存儲在一個數組中。我在 for 循環中使用 GetPixel() 得到了這個概念,然後將輸出轉換為十六進制並將 RGB 數據存儲在一個數組中,但是這種方法比我想要的要長得多。用c++讀取像素RGB數據最快的方法是什麼?
參考解法
方法 1:
Yes, GetPixel
and SetPixel
are relatively slow API calls. Manipulating individual pixels requires copying the contents of the DC (Device Context) into a temporary bitmap, mapping and locating the pixel, retrieving (or setting) its color value, and then (if the pixel's color is being set) blitting the temporary bitmap back to the device context. Once you understand all the work that is going on behind the scenes for such an apparently simple operation, you can see why it is slow. Worse, the overhead must be paid for each call to GetPixel
and/or SetPixel
, so you can see why these are not commonly used for painting operations.
The replacement approach involves the use of GetDIBits
, which is the fastest possible way of determining the values of multiple pixels. This function essentially copies the contents of the device context (DC) into a temporary device‑independent bitmap (DIB), which you can then view or manipulate as desired. Determining the color value of an individual pixel becomes as simple as indexing into that pixel's location in memory. With this approach, you can literally process millions of pixels per second. The overhead of retrieving the pixel color values is paid only once, at the very beginning.
To simulate SetPixel
, you'd manipulate the desired pixel values, then call SetDIBits
to update the device context (e.g., the screen).