Image Correction (Shading / Pixel Gain correction)
A C++ sample that applies Shading correction and Pixel Gain correction to the 1,000 fps stream of INFINICAM UC-1.1 / GbE-2 (monochrome and color) in real time, without skipping a frame, and shows the raw and corrected images side by side.
- Shading correction: subtracts the small level that each pixel outputs with no light, so that dark becomes 0.
- Pixel Gain correction: the level at which each pixel saturates differs slightly from pixel to pixel. A gain is applied so that saturation becomes 255.
The correction is written with AVX2 (CPU SIMD instructions) and takes about 0.14 ms per frame on the UC-1.1, about 0.04 ms on the GbE-2 and about 0.15 ms on the GbE-2 color (reference values). Together with decoding, it fits well within the 1 ms of a 1,000 fps frame.
| Correction | What becomes uniform | How the reference is captured | Key |
|---|---|---|---|
| Shading | level with no light → 0 | lens shaded, average of 10 frames | S |
| Pixel Gain | level at saturation → 255 | whole sensor saturated, average of 10 frames | P |

(Screen with a real camera: INFINICAM UC-1.1, 1246 x 1008, 50 fps. Left: raw, right: corrected.)
How it works
Section titled “How it works”An image sensor consists of many pixels (photodiodes). Each pixel’s characteristics differ slightly, so the same light gives slightly different values from pixel to pixel.
- Even with no light, each pixel outputs a small level (a few LSB). This is called Shading here.
- As the light increases, the output stops rising at some level (saturation). This level also differs slightly per pixel and does not necessarily reach 255.
These differences are hardly noticeable when you simply look at the image, but making them uniform gives more stable results in measurements that use brightness as a number, or in processing that uses frame differences or thresholds.
Each pixel is corrected with the following formula. The amount to subtract and the amount to multiply are prepared per pixel so that dark becomes 0 and saturation becomes 255.
out(x,y) = clamp( (in(x,y) - Shading(x,y)) * Gain(x,y), 0, 255 )
PerPixel mode : Gain(x,y) = 255 / (Saturation(x,y) - Shading(x,y))Global mode : Gain = 255 / P0.1%(Saturation - Shading) (99.9% of the pixels reach 255)The amount to subtract (Shading) and the amount to multiply (Gain) come from the following captures. Both use the average of 10 frames to reduce noise.
Before you start
Section titled “Before you start”- Make sure Continuous High-Speed Capture and OpenCV LiveView work. This sample receives the 1,000 fps stream the same way (continuous transfer with
PUC_BeginXferData) and shows it with OpenCV. - Install OpenCV in
C:\opencvas described in Setting up OpenCV (C++). - For the GbE-2, set up the network as described in PC operating environment and network settings.
What you need
Section titled “What you need”| Item | Details |
|---|---|
| Camera | INFINICAM UC-1.1 (USB) or GbE-2 (Ethernet, monochrome or color), with a lens |
| PC | Windows, CPU with AVX2 (checked at start-up) |
| Development | Visual Studio 2026, INFINICAM SDK (C:\infinicam_sdk), OpenCV 5 (C:\opencv; a project for OpenCV 4 is also included) |
| Sample | “Sample Code Bundle” in Resources & Downloads (C:\infinicam_projects) |
| Something to shade the lens | A lens cap, or a black cloth / box that blocks light |
| Bright light source | Bright light (white light for a color camera) that saturates the whole sensor evenly: an LED panel, or a strong light through a diffuser (tracing paper, opal plate, etc.) |
Try it
Section titled “Try it”1. Build
Section titled “1. Build”- Extract the “Sample Code Bundle” from Resources & Downloads to
C:\(you getC:\infinicam_projects). - Open
C:\infinicam_projects\ImageCorrection\ImageCorrection.slnxin Visual Studio. For OpenCV 4, openC:\infinicam_projects\OpenCV4\ImageCorrection\ImageCorrection.slnxinstead. - Select Release and x64 on the toolbar and build. The INFINICAM SDK and OpenCV DLLs are copied next to the executable automatically after the build.
The project uses OpenCV 5.0.0 (opencv_world500.lib), and the one in the OpenCV4 folder uses OpenCV 4.14.0 (opencv_world4140.lib). If you installed another version, change the number in the library name as described in Setting up OpenCV (C++).
2. Start
Section titled “2. Start”Connect the camera and press Ctrl + F5 in Visual Studio (or run x64\Release\ImageCorrection.exe directly). It connects to the first camera found (USB, or a GbE-2 on the network) and starts the continuous transfer at the camera’s maximum resolution and 1,000 fps.
ImageCorrection (Shading / Pixel Gain correction sample)INFINICAM GbE-2 800x600, 1000 fps, shutter 1/1000 s| Model | Resolution |
|---|---|
| UC-1.1 | 1246 x 1008 |
| GbE-2 / GbE-2 color | 800 x 600 |
The raw image (RAW) is shown on the left and the corrected image (CORRECTED) on the right. No reference has been captured yet, so both are the same at this point.
3. Capture Shading
Section titled “3. Capture Shading”- Put the lens cap on and shade the lens completely.
- Press [+] a few times to set the display gain to about x8. The small differences between pixels in the dark image become visible (the display gain is applied to the display only, not to the correction).
- Press [S]. The reference is ready after 10 frames (0.01 s at 1,000 fps), and the message line shows:
Shading reference done: mean 12.764The corrected image (right) becomes almost black. In the statistics lines, check that mean and sd (standard deviation) of CORR are smaller than those of RAW.

(Screen after capturing Shading with a real camera, display gain x1. RAW: mean 12.8, sd 2.37. CORR: mean 0.08, sd 0.30.)
4. Capture Pixel Gain
Section titled “4. Capture Pixel Gain”- Remove the lens cap and set the display gain back to x1 with [-].
- Point the camera at the bright light so that the whole image is saturated white. The focus does not matter (a blurred image is lit more evenly).
- Check that the RAW histogram is gathered at the right end. If the light is not strong enough, lower the frame rate with [F] (1,000 → 500 → 50 fps; the shutter is 1/frame rate, so a lower frame rate means a longer exposure and a brighter image).
- Press [P]. The message line shows:
Pixel Gain reference done: saturation mean 227.904, global gain 1.2085It is done when the corrected histogram (right) is gathered at 255 and sat(255) of CORR (ratio of pixels at 255) is close to 100%.
![]()
(Screen after capturing Pixel Gain with a real camera. The saturation level of RAW varies from 222 to 233 between pixels; in CORR, 96% of the pixels are 255 and the minimum is 248.)
5. Compare before / after
Section titled “5. Compare before / after”- [SPACE] freezes the view (the camera keeps running). While frozen, the current reference is re-applied to the frozen frame, so switching the mode with [G] or capturing a reference again can be compared on exactly the same image.
- Drag on the image to show the statistics and histograms of that region (ROI) only. [R] goes back to the whole image.
- A display gain of x8 - x32 makes the remaining differences in the dark areas easy to see.
Press [ESC] or close the window. The references are not saved to a file; capture them again after the next start.
Reading the screen
Section titled “Reading the screen”| Place | Shown | Meaning |
|---|---|---|
| Top | RAW / CORRECTED | Raw (left) and corrected (right) images |
| Under each image | histogram (ROI, log scale) | Histogram of the ROI (log scale). The right end is 255. With a gain, unused values appear as gaps. Color: one line each for B, G and R |
| Line 1 | LIVE / FROZEN, ROI |
Live or frozen, and the region used for the statistics |
| Lines 2-3 | mean var sd min max sat(255) of RAW / CORR |
Mean, variance, standard deviation, min, max and ratio of pixels at 255 in the ROI, computed on the real pixel values (before the display gain). Color: mean and standard deviation for each of B, G and R, and the ratio of values at 255 |
| Line 4 | Shading / Pixel Gain |
Whether each reference is captured (OK / --), its mean, and the global gain |
| Line 5 | Camera / Processed / Dropped (damaged) |
fps received from the camera, fps corrected, and dropped frames (in brackets: frames discarded because of GbE-2 packet loss) |
| Line 6 | Decode / Correction / Total |
Decode, correction and total time per frame. Total 438 / 1000 us means 438 us of the 1,000 us (1 ms) frame interval are used. Shown in red when the processing cannot keep up |
| Line 7 | Message | Result of the last operation |
| Bottom | Key guide | Available keys and current settings |
If Processed equals Camera (about 1,000 fps) and Dropped does not increase, every frame is corrected in real time.
| Key | Function |
|---|---|
| S | Capture Shading reference |
| P | Capture Pixel Gain reference |
| G | Pixel Gain mode PerPixel / Global |
| SPACE | Freeze / resume the view (the camera keeps running) |
| + / - | Display gain x1 … x64 (display only) |
| Mouse drag / R | Set the statistics region (ROI) / reset to the whole image |
| F | Frame rate 1,000 → 500 → 50 fps |
| ESC | Quit |
How the program works
Section titled “How the program works”C:\infinicam_projects\ ImageCorrection\ For OpenCV 5 ImageCorrection.slnx ImageCorrection.cpp Start here: settings, per-frame processing (callback), main loop, keys Camera.h / Camera.cpp PUCLIB part: connect, continuous transfer, decode, frame rate ImageCorrector.h Correction engine: reference capture, AVX2 correction (no OpenCV / PUCLIB dependency) LatestFrame.h Passes the latest frame to the display PerfMeter.h Counts fps, dropped frames and processing time Display.h / Display.cpp OpenCV window: images, histograms, statistics, key guide OpenCV4\ImageCorrection\ For OpenCV 4 (same source; only the OpenCV library it links is different)1. Two roles
Section titled “1. Two roles”Two roles run at the same time.
| Role | Function / place | What it does | Rate |
|---|---|---|---|
| Receive and correct | onFrame (PUCLIB thread) |
Decode, accumulate references, correct, measure time | 1,000 times per second |
| Display | while loop in main |
Take the latest frame, show it, handle keys | about 30 times per second |
PUCLIB thread (every frame, 1,000 fps) GUI thread (main, ~30 fps)-------------------------------------- ---------------------------onFrame() main loop skip damaged frame (packet loss) latestFrame.take() latest frame skip duplicated sequence number camera.decode() -> rawBuf display.show() images, histograms, info corrector.accumulate() (reference capture) handleKey() S / P / G / F / ... corrector.apply() -> correctedBuf latestFrame.store() (only when requested) perfMeter.add() fps, timeThe screen is updated only a few dozen times per second, so a copy for the display is made only when the display asks for one (LatestFrame). This keeps onFrame, which runs at 1,000 fps, light.
2. Connecting (same code for UC-1.1 and GbE-2)
Section titled “2. Connecting (same code for UC-1.1 and GbE-2)”PUC_DETECT_FILTER filter = {};filter.nDeviceTypeFlags = PUC_DETECT_TARGET_ALL; // search both UC-1.1 and GbE-2PUC_DetectDevice2(&filter, &detect);PUC_OpenDevice2(0, &h); // open the first camera foundWith PUC_DetectDevice2 and PUC_OpenDevice2, the UC-1.1 and the GbE-2 are handled by the same code. The camera is then set up in this order: frame rate → PUC_GetMaxResolution (maximum resolution at the current frame rate) → resolution → PUC_GetQuantization (quantization table for decoding). On the GbE-2 the maximum height depends on the frame rate, so the frame rate is set first.
If both models are connected, the UC-1.1, which comes first in the search result, is opened.
PUC_GetColorType tells whether the camera is color. For a color camera, PUC_DecodeDataMultiThread also performs the bayer conversion and returns BGR (3 bytes per pixel, width x 3 bytes per line), so the decode buffer must be three times larger.
3. Processing each frame
Section titled “3. Processing each frame”if (damaged) { perfMeter.addDamaged(); return; } // GbE-2: do not use a frame with packet lossif (seq == lastSeq) return; // the same frame delivered twice is processed oncecamera.decode(compressed, rawBuf.data(), DECODE_THREADS); // decode with 8 threadscorrector.accumulate(rawBuf.data(), stride); // accumulate only while capturing a referencecorrector.apply(rawBuf.data(), stride, correctedBuf.data(), stride); // correctIf the callback takes longer than 1 ms, frames are queued in the PUCLIB ring buffer (RING_BUFFER, 64 frames). When it is full, frames are dropped and counted in Dropped.
4. Correcting color images (GbE-2 color)
Section titled “4. Correcting color images (GbE-2 color)”For a color camera, each of B, G and R has its own per-pixel Shading and Gain. A BGR line is handled as a line of width x 3 values, so the correction (the AVX2 kernel) is exactly the same as for monochrome.
corrector.init(W, H, camera.channels()); // color: channels = 3, the tables are 3 times the pixel count- Saturate with white light: Pixel Gain maps the saturation level of each color to 255, so with white light, white becomes (255, 255, 255). It also works as the white balance.
- White balance left at 1.0: the white balance gain used for decoding (
PUC_SetWhiteBalanceGain) is left at its default of 1.0. If it is greater than 1, that color is clipped at 255 already in the decoder and its saturation level cannot be measured correctly. - Corrected after the bayer conversion: PUCLIB returns BGR after the bayer conversion, so the correction is applied to that image. Each color value is interpolated from neighboring pixels, so the Pixel Gain correction is somewhat milder than correcting each sensor pixel individually.
- Screen: the statistics show mean and standard deviation for each of B, G and R, and the histograms show three lines for B, G and R.
5. Making the correction fast (AVX2 and fixed point)
Section titled “5. Making the correction fast (AVX2 and fixed point)”The correction is only one subtraction and one multiplication per pixel, but the UC-1.1 has 1.25 million pixels per frame, 1,000 times per second. AVX2 instructions process 32 pixels at a time.
in16 = _mm256_cvtepu8_epi16(in) << 7 // widen 16 pixels to 16 bits, Q7 (x128)diff = _mm256_subs_epu16(in16, ShadingQ7) // subtract Shading (below 0 -> 0)out16 = _mm256_mulhrs_epi16(diff, GainQ8) // multiply by the gain, with roundingout = _mm256_packus_epi16(out16) // back to 8 bits (above 255 -> 255)- The per-frame correction uses only 16-bit integers (fixed point), no floating point. Floating point is used only once, to build the tables when a reference is captured.
- The Shading is an average of 10 frames and has a fraction (e.g. 5.4). It is kept as Q7 (x128), so fractions below 1 can be subtracted.
- The gain is kept as Q8 (x256, steps of 1/256).
- The result matches the floating point formula within 1.
- In Global mode (or before Pixel Gain is captured) the gain table is not read, which is even faster.
6. Time for the correction
Section titled “6. Time for the correction”The actual time is shown on the screen as Correction (AVX2) (average per frame). Reference values for the correction only, on a Core i9-10850K desktop PC:
| Mode | UC-1.1 (1246 x 1008) | GbE-2 (800 x 600) | GbE-2 color (800 x 600 x 3) |
|---|---|---|---|
| Shading + Pixel Gain (PerPixel) | 139 us | 40 us | 150 us |
| Shading + Pixel Gain (Global) | 123 us | 30 us | 105 us |
The speed is limited by memory bandwidth (PerPixel per frame: the UC-1.1 reads 1.25 MB input + 5 MB tables and writes 1.25 MB; the GbE-2 reads 0.48 MB + 1.9 MB and writes 0.48 MB; the GbE-2 color reads 1.44 MB + 5.8 MB and writes 1.44 MB).
Parameters
Section titled “Parameters”The main behavior is set by constants at the top of the source files. Rebuild after changing them.
| Constant | Defined in | Default | Description |
|---|---|---|---|
AVERAGE_FRAMES |
ImageCorrector.h | 10 |
Number of frames averaged for a reference. More frames reduce the noise in the reference (100 frames at 1,000 fps take 0.1 s) |
FRAMERATES[] |
ImageCorrection.cpp | { 1000, 500, 50 } |
Frame rates cycled with [F]. The first one is used at start. The shutter is 1/frame rate |
CAMERA_WIDTH / CAMERA_HEIGHT |
ImageCorrection.cpp | 0 / 0 |
Capture resolution. 0 means the maximum resolution of the connected camera |
MAX_GAIN |
ImageCorrector.h | 8.0f |
Upper limit of the Pixel Gain |
GLOBAL_PERCENTILE |
ImageCorrector.h | 0.001f |
Ratio of pixels allowed below 255 in Global mode (0.001 = 0.1%) |
MIN_RANGE |
ImageCorrector.h | 32.0f |
Minimum “Saturation − Shading” for a per-pixel gain in PerPixel mode. Pixels below it use the global gain |
DECODE_THREADS |
ImageCorrection.cpp | 8 |
Number of decode threads |
RING_BUFFER |
ImageCorrection.cpp | 64 |
Number of frames PUCLIB keeps when the processing is late |
WINDOW_MAX_WIDTH |
ImageCorrection.cpp | 1600 |
Maximum window width (pixels) |
Troubleshooting
Section titled “Troubleshooting”| Symptom | Main cause | What to do |
|---|---|---|
ERROR: No INFINICAM detected |
Camera not found | Check the USB cable (UC-1.1), or the LAN cable and the network settings (GbE-2) |
ERROR: this sample requires a CPU with AVX2 |
CPU without AVX2 | Use a PC with AVX2 |
| OpenCV headers or libraries not found in the build, or a DLL not found at start | Location or version of OpenCV differs | See Troubleshooting in Setting up OpenCV (C++) |
Processed below Camera, Total in red |
Processing cannot keep up | Check that it is a Release build. Close other applications |
Dropped or damaged increases (GbE-2) |
Network settings | Check jumbo packets etc. in PC operating environment and network settings |
| Corrected image does not reach 255 after Pixel Gain | Sensor was not saturated | Make the light stronger until the RAW histogram is at the right end, or lower the frame rate with [F], then capture again. Or use Global mode with [G] |
| Unevenness remains in the corrected image | Conditions changed | The Shading can depend on shutter, frame rate, resolution and temperature. Capture again after changing the conditions |
Frame rate change failed: ... needs a smaller resolution |
The current resolution is not possible at that frame rate | Review FRAMERATES, or make CAMERA_HEIGHT smaller |
Using it in your own program
Section titled “Using it in your own program”The correction engine ImageCorrector.h is a single header file. It depends on neither OpenCV nor PUCLIB, so copy it into your project and #include it to use the same correction.
- Requirements: C++14 or later, a CPU with AVX2
- AVX2 is enabled per function, so no compiler option such as
/arch:AVX2is needed. - The input is a decoded 8-bit image (e.g. the output of
PUC_DecodeDataMultiThread): monochrome, or the BGR of the GbE-2 color.
#include "ImageCorrector.h"
using photron::ImageCorrector;ImageCorrector corrector;
// Once at start: check AVX2 and set the image sizeif (!photron::cpuSupportsAVX2()) { /* AVX2 not supported */ }corrector.init(width, height); // GbE-2 color (BGR): init(width, height, 3)
// Start capturing a reference (Shading with the lens shaded, PixelGain with the sensor saturated)corrector.beginReference(ImageCorrector::Reference::Shading);
// Every frame (stride = bytes per line)corrector.accumulate(raw, stride); // accumulates only while capturing; done after 10 framescorrector.apply(raw, stride, corrected, stride); // writes the corrected image to corrected
// Has the capture finished?bool done = corrector.capturingReference() == ImageCorrector::Reference::None;| Function | Description |
|---|---|
init(width, height, channels) |
Sets the image size and the number of channels (1: monochrome, 3: BGR, default 1) and resets the references (no correction) |
beginReference(ref) |
Starts capturing a reference (Shading / PixelGain) |
accumulate(src, stride) |
Adds one frame while capturing. The reference is complete after AVERAGE_FRAMES frames |
apply(src, srcStride, dst, dstStride) |
Corrects an image |
capturingReference() |
Reference being captured (None when finished) |
setGainMode(mode) |
Switches PerPixel / Global |
summary() |
Whether references exist, their means, the global gain, etc. |
shadingReference() / saturationReference() |
Reference values (float, per pixel; BGR order for color) |
Points to note:
- Threads: an internal mutex guards the state, so
accumulate/applycan be called from the receive callback whilebeginReferenceorsetGainModeare called from the GUI. - Combine with Applications: call
applyright after decoding to analyze corrected images. Processing based on brightness differences or thresholds tends to become more stable. - Saving the references: this sample does not save the references to a file. Save the values of
shadingReference()/saturationReference()and load them at start to skip capturing every time (under the same conditions). - For measurements: keep the corrected values in 16 bits instead of 8 bits to reduce the gaps (unused values) caused by the gain and the effect of clipping at 0.
