Matlab Enhance Camera Image
MathWorksOfficialCreated by MathWorks
- Skill
- Workflow
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, hardware-first approach to troubleshooting and enhancing images from cameras connected via MATLAB. It guides users through discovering camera capabilities, diagnosing quality issues like poor exposure, noise, or blur, and applying targeted hardware adjustments followed by software-based post-processing. The workflow emphasizes fixing issues at the source before using Image Processing Toolbox functions, ensuring optimal results for scientific and technical imaging tasks.
What it does
- Diagnoses image quality metrics including brightness, contrast, sharpness, noise, and color balance.
- Discovers and reports camera hardware properties at runtime for precise adjustment.
- Provides a decision table to map specific quality issues to hardware or software fixes.
- Applies Image Processing Toolbox functions in a recommended order to prevent quality degradation.
- Generates a reusable, custom MATLAB function for automated future image acquisition and enhancement.
- Supports both Image Acquisition Toolbox and USB Webcam support package interfaces.
When to use it
- When a camera feed appears too dark, blurry, noisy, or washed out.
- When you need to optimize camera settings for a specific scientific or technical application.
- When you need to perform consistent, repeatable image enhancement on captured frames.
- When you want to diagnose whether an image issue is caused by hardware settings or requires software correction.
Advantages
- Prioritizes hardware-level adjustments to maintain original image integrity.
- Prevents common pitfalls like sharpening noise or misinterpreting YUY2 color spaces.
- Automates the creation of custom acquisition pipelines for future use.
- Provides objective diagnostic metrics to quantify image quality improvements.
Usage examples
- “My camera image is very dark and noisy. Can you help me fix it?”
- The agent will connect to the camera, run a diagnostic to quantify the brightness and noise levels, suggest specific hardware adjustments like increasing exposure or reducing gain, and then apply denoising filters if necessary.
- “I need a script to capture images from my webcam that are always sharpened and brightened.”
- The agent will guide you through the manual tuning process to find the best settings, then generate a custom .m file that automates the connection, capture, and post-processing steps for future use.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/matlab/matlab-enhance-camera-image/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-enhance-camera-image.zip -d .agents/skills
Documentation by MathWorks
Purpose
Diagnose image quality issues from any connected camera and improve them through a combination of hardware setting adjustments and software post-processing. Operates in a hardware-first, software-second philosophy: always try to fix at the source before resorting to post-processing.
When to Use
User complains about poor image quality from a camera (too dark, blurry, noisy, washed out)
User asks how to improve or optimize camera settings
User captures an image and wants to enhance it
User mentions backlit subject, underexposed, overexposed, or out of focus
When NOT to Use
General image processing on files not from a camera (use IPT directly)
Building an image acquisition pipeline from scratch (use Image Acquisition Toolbox docs)
Camera geometric calibration (use Camera Calibrator app)
Reference Documents (load when needed)
Read references/diagnosis-guidance.md for detailed metric thresholds and backlight detection algorithms
Read references/hardware-tuning-guidance.md for property discovery patterns, camera-type property tables, and safe adjustment strategies (applicable to all camera types)
Read references/enhancement-guidance.md for IPT function parameters, pipeline ordering, and common errors
Script Entrypoints
scripts/diagnoseImageQuality.m— reusable diagnostic function; takes an image, returns a struct of quality metrics with assessments
Hard Requirements
Call
detect_matlab_toolboxesfirst to confirm Image Acquisition Toolbox and Image Processing Toolbox are installedCall
check_matlab_codeon any script before executing itNever hardcode camera property names — always discover at runtime
Protocol
Step 1 — Connect and Discover Camera Capabilities
API selection: When Image Acquisition Toolbox is available, always prefer videoinput over other interfaces like webcam(). videoinput exposes more properties (via propinfo), supports bulk frame acquisition (getdata), and provides FramesAcquiredFcn for streaming. Use webcam() only when Image Acquisition Toolbox is not installed and the user has the MATLAB Support Package for USB Webcams instead.
Connect to the camera and enumerate all available properties:
% For videoinput (preferred when Image Acquisition Toolbox is available):
vid = videoinput(adaptorName, deviceID, format);
vid.ReturnedColorSpace = 'rgb'; % Critical for YUY2 cameras
src = getselectedsource(vid);
props = properties(src);
% For webcam (fallback when only USB Webcams support package is installed):
cam = webcam();
props = properties(cam);Classify each discovered property by function:
| Problem Domain | Common Property Names |
|---|---|
| Brightness/Exposure | Exposure, ExposureTime, ExposureMode, Brightness, Gain, BacklightCompensation |
| Focus | Focus, FocusMode |
| Color | WhiteBalance, WhiteBalanceMode, Hue, Saturation, ColorEnable |
| Contrast/Tone | Contrast, Gamma, Sharpness |
Record valid ranges for each property. Report discovered capabilities to the user.
For properties that do NOT match the classification table above, apply the advanced property investigation protocol:
Group unrecognized properties by naming pattern (e.g., names containing "Trigger", "Pixel", "Bin", "LUT", "ROI", "Offset", "Decimation")
For
videoinputsources, usepropinfo(src, propName)to determine type, constraint, range, and read-only statusClassify as quality-relevant (likely affects image appearance: Binning, BlackLevel, LUT, DigitalGain, HDR) vs functional (affects acquisition mode, not quality: TriggerMode, PixelFormat, PacketSize, AcquisitionFrameRate)
Report all discovered properties to the user, distinguishing standard (known) from advanced (discovered)
For quality-relevant unknowns, follow the safe investigation protocol in references/hardware-tuning-guidance.md
Step 2 — Capture Baseline Image
For videoinput objects (preferred):
% Warm up the camera (critical — first frames are often blank or poorly exposed)
preview(vid);
pause(2);
closepreview(vid);
% Capture the reference image
baselineImg = getsnapshot(vid);
imshow(baselineImg);
title("Baseline Image");For webcam objects (fallback):
% Warm up the camera (critical — first frames are often blank or poorly exposed)
preview(cam);
pause(2);
closePreview(cam);
% Capture the reference image
baselineImg = snapshot(cam);
imshow(baselineImg);
title("Baseline Image");Note: snapshot() is webcam-only. For videoinput, use getsnapshot(vid). Both webcam and videoinput objects support preview().
Record current property values as baseline for comparison.
Step 3 — Understand User Concern
Before running diagnostics, identify what the user is trying to fix:
If the user already stated a specific complaint (e.g., "image is too dark", "I see banding"), note it as the primary concern
If the user has not stated a specific issue, ask: "What specific quality issue are you seeing, or would you like me to run a general assessment?"
If the user says "just make it better" or has no specific concern, proceed with the standard 6-metric evaluation only
Map the user's concern to one of these categories:
Standard metrics (covered by
diagnoseImageQuality.m): brightness, contrast, sharpness, noise, color balance, backlightingExtended concerns (require dynamic inline evaluation): vignetting, banding/striping, saturation clipping, flicker/inconsistency, chromatic aberration, distortion, or other
If the concern is an extended one, note it for dynamic evaluation in Step 4.
Step 4 — Diagnose Image Quality
Run the diagnostic script (always — provides the standard baseline):
addpath("scripts");
results = diagnoseImageQuality(baselineImg);
disp(results);The function returns a struct with fields:
brightness— mean intensity, assessmentclipping— highlight clipping (% pixels ≥ 250) and shadow clipping (% pixels ≤ 5), assessmentcontrast— standard deviation, assessmentsharpness— Laplacian variance, assessmentnoise— estimated noise level, assessmentcolorBalance— R/G and B/G ratios, assessmentbacklightRatio— center-vs-border brightness ratio, assessment
Each field has .value (numeric or struct) and .assessment ("OK", "Problem", or "Severe").
Identify the primary issue(s) — focus on fields assessed as "Problem" or "Severe".
Dynamic evaluation for extended concerns: If the user's concern from Step 3 is not covered by the standard 6 metrics, generate inline MATLAB code to evaluate it. See references/diagnosis-guidance.md § "Extended Metrics" for evaluation patterns and code templates. Report the extended metric result alongside the standard results.
Step 5 — Suggest Hardware Adjustments
Map diagnosed problems to available camera properties using the decision table below. Only suggest adjustments for properties the camera actually has.
Apply settings, re-capture, and compare metrics. Change one property at a time.
For videoinput objects (preferred):
% Example: increase exposure for dark image
src.Exposure = src.Exposure + 2;
newImg = getsnapshot(vid);
newResults = diagnoseImageQuality(newImg);For webcam objects (fallback):
% Example: increase exposure for dark image
cam.Exposure = cam.Exposure + 2;
newImg = snapshot(cam);
newResults = diagnoseImageQuality(newImg);Note: With videoinput, set properties on the source object (src), not the videoinput object. Use getsnapshot(vid) instead of snapshot().
Iterate if needed until metrics improve or hardware options are exhausted.
Step 6 — Apply Post-Processing Enhancement
Based on remaining issues after hardware adjustment, apply IPT functions in the correct order:
Brighten (if still dark):
imlocalbrighten,imadjust, gamma correctionContrast (if still flat):
locallapfilt,adapthisteqon luminance channelSharpen (if still soft):
imsharpen— always last
enhanced = baselineImg;
% Example: brighten a backlit image
enhanced = imlocalbrighten(enhanced, 0.8);
% Example: enhance local contrast
enhanced = locallapfilt(enhanced, 0.3, 1.5);
% Example: sharpen (last step)
enhanced = imsharpen(enhanced, 'Radius', 1.5, 'Amount', 1.0);Display before/after comparison:
montage({baselineImg, enhanced}, 'Size', [1 2]);
title("Before vs After Enhancement");Step 7 — Report and Generate Reusable Pipeline
Summarize the full workflow:
Original problem identified
Hardware adjustments applied and their effect
Software enhancements applied
Final metrics comparison (before vs after)
Generate a reusable .m function file that the user can call for future captures without the agent. Write it to a user-specified folder if provided, otherwise to the current MATLAB working directory (pwd). Do NOT write it to the skill's scripts/ folder — that is reserved for the skill's own helper functions.
After writing the file:
Run
check_matlab_codeon it to verify syntaxShow the user how to call it
Explain which settings and enhancements are baked in
Single-Shot Pipeline
The function should:
Connect to the camera with the discovered adaptor, device ID, and format
Set
ReturnedColorSpace = 'rgb'if the camera outputs YUY2 or other non-RGB formatApply the tuned hardware property settings that improved metrics
Warm up the camera (discard initial frames)
Capture a frame
Apply only the post-processing steps that measurably improved quality (in correct order)
Clean up (stop and delete the videoinput object)
Return the enhanced image
Decision Table
| Diagnosed Problem | Hardware Fix (if available) | Software Fix (IPT) |
|---|---|---|
| Subject too dark (backlit) | BacklightCompensation ↑, Exposure ↑, Brightness ↑ | imlocalbrighten, inverted imreducehaze |
| Overall underexposed | Exposure ↑, Gain ↑, Brightness ↑ | Gamma correction (.^ 0.7), imadjust |
| Overall overexposed | Exposure ↓, Brightness ↓ | imadjust with output range [0 0.8] |
| Low contrast | Contrast ↑, Gamma adjust | locallapfilt, adapthisteq on luminance |
| Motion blur | Exposure ↓ (faster shutter) | imsharpen (limited), deconvolution |
| Out of focus | Focus adjust (if available) | imsharpen (limited help) |
| High noise | Gain ↓, Exposure ↑ instead | imgaussfilt, imnlmfilt, wiener2 |
| Color cast | WhiteBalance adjust, WhiteBalanceMode=auto | Manual white point correction |
| Washed out | Gamma ↓, Contrast ↑ | imadjust, locallapfilt |
Generated Pipeline Templates
Replace placeholders with discovered values. Only include enhancement steps that measurably improved metrics.
Single-Shot Template (videoinput)
function img = acquireEnhancedImage()
%acquireEnhancedImage Capture and enhance image from <camera name>.
% img = acquireEnhancedImage() returns an enhanced RGB image.
vid = videoinput('<adaptor>', <deviceID>, '<format>');
vid.ReturnedColorSpace = 'rgb';
src = getselectedsource(vid);
% Tuned hardware settings
src.<Property1> = <value>;
src.<Property2> = <value>;
% Warm up
preview(vid);
pause(2);
closepreview(vid);
% Capture
img = getsnapshot(vid);
delete(vid);
% Enhancement pipeline (only steps that helped)
img = imlocalbrighten(img, <amount>);
img = imgaussfilt(img, <sigma>);
endNaming: use acquireEnhancedImage as default, or ask user for a preferred name. Follow lowerCamelCase. See references/enhancement-guidance.md § "Generating Reusable Functions" for parameterization and optional-input guidance.
Gotchas
localtonemaprequiressingleinput — always convert withim2single()first; passing uint8 throws an errorCamera warm-up is critical — first 5–10 frames are often blank or poorly exposed. Use
preview()or discard initial snapshots before capturingadapthisteq(CLAHE) needs a single-channel image — apply on V channel (HSV) or L channel (Lab), not directly on RGBPrefer Exposure over Gain — when a camera has both, increasing Exposure gives cleaner results; Gain amplifies noise
BacklightCompensation range varies — some cameras 0–1, others 0–2, others 0–255. Always check range at runtime
imlocalbrightenonly lifts dark regions — preserves already-bright areas; preferred over global brightness increase for backlit scenesPost-processing order matters — brighten first, then local contrast, then sharpen last. Sharpening amplifies noise if applied before denoising
Auto modes override manual values — set ExposureMode/WhiteBalanceMode to manual before adjusting the corresponding value
Resolution changes may reset properties — re-check property values after changing resolution
YUY2 cameras need
ReturnedColorSpace = 'rgb'— many USB webcams (e.g., Microsoft LifeCam) only output YUY2. Without settingvid.ReturnedColorSpace = 'rgb',getsnapshotreturns raw YCbCr data misinterpreted as RGB, causing wrong colors in display AND incorrect results from IPT functions and diagnostic metricssnapshotvsgetsnapshot—snapshot(cam)is webcam-only;getsnapshot(vid)is for videoinput objects. They are not interchangeableclosePreviewvsclosepreview— webcam uses camelCaseclosePreview(cam); videoinput uses lowercaseclosepreview(vid). Using the wrong case throws "Undefined command/function"videoinput prefers bulk
getdata— for multi-frame capture with videoinput, usegetdata(vid, N)instead of loopinggetsnapshot. It fetches N frames in one call with less overhead and lets the adaptor run at full speedUse
fullfilefor file saves — when saving images or generated files, usefullfile(pwd, 'filename.png')to avoid path resolution errors across platforms
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md14.8 KiB
- manifest.yaml548 B
- references/diagnosis-guidance.md8.4 KiB
- references/enhancement-guidance.md8.8 KiB
- references/hardware-tuning-guidance.md9.2 KiB
- scripts/diagnoseImageQuality.m4.5 KiB
references/enhancement-guidance.md
Enhancement Guidance — IPT Functions, Parameters, and Pipelines
Pipeline Ordering Rules
Apply post-processing in this order. Violating the order degrades results:
Brighten — lift shadows and correct exposure
Contrast — enhance local/global contrast
Sharpen — enhance edges (last, because it amplifies noise)
Denoise — only if noise is still problematic after other steps; apply before sharpening if noise is severe
Why this order matters:
Sharpening amplifies whatever is in the image — apply after denoising
Contrast enhancement on a dark image exaggerates noise in shadows — brighten first
Denoising after sharpening blurs the edges you just enhanced
Function Reference
Brightening / Exposure Correction
imlocalbrighten
out = imlocalbrighten(img);
out = imlocalbrighten(img, amount);amount: 0–1 (default 1.0). Use 0.5–0.9 for moderate to strong brightening
Only lifts dark regions; preserves already-bright areas
Preferred for backlit scenes over global brightness increase
Input: uint8/uint16/single RGB or grayscale
Does not require conversion
Gamma Correction (manual)
out = imadjust(img, [], [], gamma);gamma < 1: brightens (e.g., 0.6–0.8 for moderate brightening)
gamma > 1: darkens
Alternative:
img .^ gammaon double/single images
imadjust
out = imadjust(img); % Auto stretch to [0, 1]
out = imadjust(img, [low_in high_in], [low_out high_out]);Stretches intensity range linearly
For overexposed images:
imadjust(img, [], [0 0.8])compresses output rangeOperates per-channel on RGB (may shift color balance)
Inverted imreducehaze (shadow lifting)
out = imreducehaze(imcomplement(img));
out = imcomplement(out);Treating shadows as "haze in the inverted image" lifts dark regions
Useful when
imlocalbrightenis too aggressive
Contrast Enhancement
locallapfilt (Local Laplacian Filter)
out = locallapfilt(img, sigma, alpha);sigma: edge threshold (0.1–0.5). Lower = only enhance fine details
alpha: enhancement amount. >1 enhances, <1 smooths
Recommended: sigma=0.2–0.4, alpha=1.2–2.0 for moderate enhancement
Input: uint8/uint16/single/double
Excellent for natural-looking local contrast without halos
adapthisteq (CLAHE)
out = adapthisteq(grayImg);
out = adapthisteq(grayImg, 'ClipLimit', 0.02, 'NumTiles', [8 8]);CRITICAL: Operates on single-channel images only
For RGB: convert to Lab, apply to L channel, convert back:
lab = rgb2lab(img); lab(:,:,1) = adapthisteq(uint8(lab(:,:,1) * 255 / 100)) * 100 / 255; out = lab2rgb(lab, 'OutputType', 'uint8');ClipLimit: 0.01–0.05 (lower = less enhancement, fewer artifacts)
NumTiles: [8 8] default; larger tiles = more global effect
localtonemap
out = localtonemap(imgSingle);CRITICAL: Requires
singleinput — always convert withim2single()firstDesigned for HDR images but works on standard images for extreme contrast recovery
May produce unnatural results on well-exposed images
Sharpening
imsharpen
out = imsharpen(img);
out = imsharpen(img, 'Radius', R, 'Amount', A);Radius: 1–3 (size of blur kernel; larger = coarser sharpening)
Amount: 0.5–2.0 (strength; >2 risks halos)
Threshold: 0–1 (skip sharpening for low-contrast edges to avoid noise amplification)
Recommended starting point: Radius=1.5, Amount=1.0, Threshold=0.1
Limited help for out-of-focus images — cannot recover lost information
deconvwnr / deconvlucy (deconvolution)
out = deconvwnr(img, psf, nsr);
out = deconvlucy(img, psf, numIterations);Requires estimating the PSF (point spread function)
For motion blur:
psf = fspecial('motion', len, angle)For defocus:
psf = fspecial('disk', radius)Aggressive — can introduce ringing artifacts. Use conservatively.
Noise Reduction
imgaussfilt
out = imgaussfilt(img, sigma);sigma: 0.5–2.0 (higher = more smoothing, more detail loss)
Fast and simple; good for light noise
Blurs edges — prefer
imnlmfiltfor better edge preservation
imnlmfilt (Non-Local Means)
out = imnlmfilt(img);
out = imnlmfilt(img, 'DegreeOfSmoothing', dos);DegreeOfSmoothing: auto-estimated if omitted; override for control
Preserves edges better than Gaussian; slower
Good default for moderate noise
wiener2
out = wiener2(grayImg, [m n]);[m n]: neighborhood size (default [3 3]; try [5 5] for stronger denoising)
Grayscale only — apply per-channel for RGB
Adaptive — adjusts based on local variance
Color Correction
Manual White Point Correction
imgDouble = im2double(img);
rScale = targetGray / mean(imgDouble(:,:,1), "all");
gScale = targetGray / mean(imgDouble(:,:,2), "all");
bScale = targetGray / mean(imgDouble(:,:,3), "all");
out = imgDouble .* cat(3, rScale, gScale, bScale);
out = im2uint8(min(out, 1.0));targetGray: typically 0.5 or the mean of the green channelSimple but effective for uniform color casts
Input Type Requirements Summary
| Function | Required Input Type | Conversion |
|---|---|---|
localtonemap | single | im2single(img) |
adapthisteq | uint8 single-channel | Extract L or V channel |
imlocalbrighten | uint8/uint16/single | Usually no conversion needed |
locallapfilt | uint8/uint16/single/double | Usually no conversion needed |
imsharpen | uint8/uint16/single/double | Usually no conversion needed |
wiener2 | double grayscale | im2double(grayImg) |
imnlmfilt | uint8/uint16/single | Usually no conversion needed |
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
Expected input to be single | localtonemap received uint8 | im2single(img) before calling |
Expected 2-D input | adapthisteq received RGB | Extract luminance channel first |
Output contains values > 1 | Operations on double without clamping | min(max(out, 0), 1) or im2uint8 |
| Halos around edges after sharpening | imsharpen Amount too high | Reduce Amount to 0.8–1.2 |
Color shift after imadjust on RGB | Per-channel stretch changes ratios | Convert to Lab, adjust L only |
| Noise amplified after sharpening | Sharpened before denoising | Reorder: denoise first, then sharpen |
Generating Reusable Functions
After the diagnosis and tuning workflow, generate a .m function file the user can call repeatedly without the agent.
What to include
Only include enhancement steps that measurably improved at least one metric during the session. If a step was tried and reverted (no improvement), omit it.
Hardcoded vs parameterized values
Hardcode camera-specific settings that won't change between captures (adaptor name, device ID, format, ReturnedColorSpace, tuned property values)
Parameterize values the user may want to adjust per-capture. Use an
argumentsblock:
function img = acquireEnhancedImage(options)
arguments
options.BrightenAmount (1,1) double = 0.8
options.DenoiseSigma (1,1) double = 0.8
end
% ... acquisition code ...
img = imlocalbrighten(img, options.BrightenAmount);
img = imgaussfilt(img, options.DenoiseSigma);
endUse parameterization when the user expressed interest in adjusting strength, or when the optimal value depends on scene conditions that may vary.
Optional image input (skip acquisition)
If the user wants to reuse only the enhancement pipeline on pre-captured images, add an optional input:
function img = acquireEnhancedImage(options)
arguments
options.InputImage (:,:,:) uint8 = uint8.empty
options.BrightenAmount (1,1) double = 0.8
end
if isempty(options.InputImage)
% ... full acquisition code ...
else
img = options.InputImage;
end
% ... enhancement pipeline ...
endvideoinput type validation
videoinput is not a standard MATLAB class. It cannot be used as a class validator in arguments blocks:
% THIS FAILS at runtime:
function stopCapture(vid)
arguments
vid (1,1) videoinput % Error: 'videoinput' is not recognized as a class
end
endUse an isa guard in the function body instead:
function stopCapture(vid)
if ~isa(vid, "videoinput") || ~isvalid(vid)
error("Expected a valid videoinput object.");
end
% ... rest of function ...
endNaming conventions
Function name: lowerCamelCase, verb-phrase (e.g.,
acquireEnhancedImage,captureCleanFrame)File name must match function name:
acquireEnhancedImage.mOne-line H1 help comment describing what it does
Keep the function under 50 lines where possible
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/test-and-measurement/matlab-enhance-camera-image · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-enhance-camera-image.zip