System designTroubleshooting

MATLAB videoinput shows wrong colors: fix the color space

Green and purple stripes mean videoinput returns YCbCr planes that image() reads as RGB. Wrong colors? Pick an RGB24 format or set ReturnedColorSpace to rgb.

LumaSpec Vision9 min read Share on LinkedIn

On this page 9 sections
  1. 01What the stripes tell you
  2. 02Rank the causes, then test the one on top
  3. 03Fix 1: create the object with an RGB24 device format
  4. 04Fix 2: keep YUY2 and convert the YCbCr planes
  5. 05Worked example: a 640 × 480 YUY2 webcam at 30 fps
  6. 06Check the fix with a white and a red target
  7. 07When the wrong colors come from somewhere else
  8. 08Keep the next bring-up clean
  9. 09Questions

You have a working videoinput object, preview runs, and the frame you show with image() is a green-and-purple striped mess. The code is usually fine: the camera is sending video in a packed YUV format, most often YUY2, and the toolbox hands you its Y, Cb and Cr values as an M-by-N-by-3 uint8 array. Every MATLAB display function reads that shape as RGB, so the colors are scrambled by interpretation, not by the camera. Here you confirm which format your winvideo device is using, apply the two fixes in the order to try them, and run the byte-count arithmetic that picks between them for your resolution and frame rate. The last sections cover the related faults: gray frames, colors that break only after the frame leaves MATLAB, and what changes when the camera is a machine-vision model rather than a USB webcam.

What the stripes tell you

A frame that arrives striped green and magenta, with bands repeating every 2 pixels, is YCbCr data being read as RGB. The device format behind it is almost always YUY2, which packs 4 bytes per 2 pixels in the order Y1 U Y2 V: each pixel carries its own luma byte, and a Cb and a Cr byte are shared by each pixel pair. getsnapshot returns the frame de-packed into three full-size planes — Y, Cb and Cr — as a 480-by-640-by-3 uint8 array in the 640 × 480 case. image(), imshow() and imagesc() receive no format metadata with the array, so an M-by-N-by-3 uint8 block always reads as RGB. The luma plane lands in the red slot and the chroma planes land in green and blue, which is why the image carries a green tint with magenta banding that no white-balance setting can undo.

Rank the causes, then test the one on top

Work down this table; the first row covers nearly every case with these symptoms.

What you see Likely cause Test Where it is fixed
Green and magenta stripes with a 2-pixel period YUY2 device format (packed 4:2:2) get(vid, 'VideoFormat') starts with YUY2 Fix 1 or fix 2
Stripes plus blockiness repeating every 2 lines 4:2:0 family (YUV420) format name contains 420 Fix 1 or fix 2
Colors right in MATLAB, swapped in another viewer channel order after acquisition frame looks wrong only outside MATLAB OpenCV note below
Flat gray image, no stripes at all wrong format or adaptor size(frame) returns 2 dimensions gray-image article below

One diagnostic snapshot is worth more than a guess: run frame2 = getsnapshot(vid); size(frame2). Three dimensions with stripes means the planes are present and the color space is the fault. Two dimensions means the adaptor matched a mono format, and you are debugging the wrong layer.

Fix 1: create the object with an RGB24 device format

The cleanest fix costs one argument. Select a device format whose name starts with RGB24 and the toolbox delivers true RGB with no conversion on your side.

  1. List the cameras: imaqhwinfo('winvideo') returns the DeviceIDs.
  2. Read the format list for your device: info = imaqhwinfo('winvideo', 1), then open info.SupportedFormats. Every entry pairs a color format with a resolution, for example YUY2_640x480 and RGB24_640x480.
  3. Clear stray objects with delete(imaqfind). A forgotten object keeps the device busy, and a second videoinput call on the same camera errors out.
  4. Create the object with the format string copied exactly from that list: vid = videoinput('winvideo', 1, 'RGB24_640x480');
  5. Run start(vid) and snapshot. The array is RGB in image(), imshow() and in every file you save from it.

The names come from the driver, so copy them out of SupportedFormats rather than typing a plausible one; a device that lists RGB24 only at lower resolutions will not accept RGB24_640x480.

info = imaqhwinfo('winvideo', 1);
celldisp(info.SupportedFormats)     % names such as 'YUY2_640x480', 'RGB24_640x480'
delete(imaqfind)                    % release the device before recreating
vid = videoinput('winvideo', 1, 'RGB24_640x480');

Fix 2: keep YUY2 and convert the YCbCr planes

If the camera lists no RGB24 entry at your resolution, or only at frame rates you cannot use, keep the YUY2 device format and convert.

  1. Create the object as before: vid = videoinput('winvideo', 1);
  2. Set the returned color space before start(vid): set(vid, 'ReturnedColorSpace', 'rgb'); The toolbox then converts the YCbCr planes to RGB when getsnapshot runs.
  3. To keep the raw planes for processing, set ReturnedColorSpace to 'YCbCr', snapshot, and convert for display only with rgb = ycbcr2rgb(frame); — the function follows the standard YCbCr definition and returns the same size and class.
  4. To track brightness only, set it to 'grayscale'; the toolbox returns the luma plane and skips color entirely.

If you would rather decode the packed bytes yourself, byte order and offsets included, there is a separate walkthrough on decoding raw YUYV frames in MATLAB.

vid = videoinput('winvideo', 1);            % YUY2 device format stays
set(vid, 'ReturnedColorSpace', 'rgb');      % set before start
start(vid);
rgb = getsnapshot(vid);                     % 480x640x3 uint8, true RGB

Worked example: a 640 × 480 YUY2 webcam at 30 fps

This is the case the first table row usually hides: a USB webcam whose SupportedFormats lists YUY2_640x480 at 30 fps and an RGB24_640x480 entry only at a lower rate.

Inputs: 640 × 480 pixels and 30 fps come from the format strings; YUY2 packs 2 bytes per pixel and RGB24 packs 3, which the format names encode; the chroma pair is shared by 2 pixels, which is where the 2-pixel stripe period comes from.

bytes per frame = width × height × bytes per pixel MB per second = bytes per frame × frame rate / 1,000,000

Arithmetic:

  • Pixels per frame: 640 × 480 = 307,200.
  • YUY2: 307,200 px × 2 bytes/px = 614,400 bytes/frame; at 30 fps that is 614,400 × 30 = 18,432,000 bytes/s, about 18.4 MB/s.
  • RGB24: 307,200 px × 3 bytes/px = 921,600 bytes/frame; at 30 fps that is 921,600 × 30 = 27,648,000 bytes/s, about 27.6 MB/s.
  • Difference: 921,600 − 614,400 = 307,200 bytes/frame, and 921,600 / 614,400 = 1.5, so RGB24 costs 50% more per frame — 9.2 MB/s more at this rate.

Result: at 640 × 480 and 30 fps, the RGB24 stream carries 27.6 MB/s where YUY2 carries 18.4 MB/s.

Decision: if SupportedFormats shows an RGB24 entry at your resolution and frame rate, take fix 1 and spend the extra 9.2 MB/s of link traffic on true RGB. If RGB24 appears only at 15 fps or below on your camera — the trade drivers usually make for the bigger format — stay on YUY2 at 30 fps and take fix 2, which keeps the link at 18.4 MB/s and converts on the host.

Check the fix with a white and a red target

Fill the frame with white paper and read the channel means:

m = squeeze(mean(mean(frame, 1), 2))    % the three channel means, returned as doubles

White passes when all three means sit above 200 and within 10 counts of each other: equal-energy white gives equal channels, so a wider spread means the color space is still wrong or the driver's white balance is off. Then point at a saturated red target: the red mean should sit at least 100 counts above green and blue (red tape typically reads near R 190 with G and B below 80). Finish by zooming the display to 100% — the 2-pixel stripes must be gone. A white spread beyond 20 counts after both fixes usually traces to the driver's white-balance setting on the source object, which getselectedsource(vid) exposes, not to the color-space conversion.

When the wrong colors come from somewhere else

  • A flat gray frame is a different fault: the adaptor matched a mono or single-plane format, and no conversion paints color into a 2-D array. The format-mismatch path is covered by Camera preview shows a gray image.
  • A GigE camera that returns no color at all usually has its pixel format parked on a mono default inside the camera; the fix lives there, not in the display code — see GigE camera shows no color image.
  • Frames that leave MATLAB meet a new convention: OpenCV expects BGR where MATLAB hands you RGB, so red and blue trade places. The channel-order fix is in converting recorded frames to BGR or RGB for OpenCV, and a frame that grows a fourth plane near a UVC device is the alpha byte in RGB32, not a color shift.
  • A machine-vision camera never appears in winvideo at all. That adaptor lists USB Video Class devices only; GigE Vision and USB3 Vision cameras are acquired through the manufacturer SDK or a GenTL interface, and CoaXPress or Camera Link models through frame grabbers. The hardware side of the same symptom starts with the area scan cameras range.

Wrong colors on a display are a mapping fault far more often than a broken device, and the pattern reaches past vision: two HMIs can show the same valve status in different colors when their state-to-color mappings differ. The cure is the same discipline — decide what the data is, then make the display agree.

Keep the next bring-up clean

A camera that delivered YUY2 once will deliver it again on the next machine, so leave the fix behind in the project:

  • Run imaqhwinfo('winvideo', 1) before writing acquisition code and record the exact format string you pass to videoinput.
  • Set ReturnedColorSpace at creation, before start(vid).
  • Snapshot a white target on the first bring-up and store the three channel means next to the code.
  • Call delete(imaqfind) before rebuilding the pipeline so a stray object never holds the device.
  • Comment the line where YCbCr becomes RGB; the next reader starts there.

More display-path fixes sit on the systems topic page. If the camera behind this problem is a machine-vision model rather than a webcam, the acquisition path changes but the discipline does not: the camera finder filters cameras by interface and resolution, and the camera configurator walks the surrounding lens, cable and frame-grabber choices.

Questions

What is YUY2 and why do webcams default to it?

YUY2 is packed YCbCr 4:2:2, one of the uncompressed formats the USB Video Class defines. Each pixel keeps its own luma byte while a Cb and a Cr pair is shared between two horizontal neighbours, so a frame costs 2 bytes per pixel instead of the 3 that RGB24 needs. Drivers default to it because it cuts the stream by a third; RGB24 entries often appear only at lower frame rates on the same camera.

Does ycbcr2rgb work directly on the array getsnapshot returns?

Yes, when the object runs a YUY2 device format and returns its three planes as Y, Cb and Cr. Pass the M-by-N-by-3 uint8 array straight in: ycbcr2rgb applies the standard ITU-R BT.601 definition and returns an array of the same size and class. Run it only once — if ReturnedColorSpace is already 'rgb', the data is RGB, and a second conversion shifts every color.

How do I check a videoinput object that already exists?

imaqfind returns every live object, which matters because a forgotten object keeps the device busy and blocks a new one. get(vid, 'VideoFormat') shows the selected device format, for example YUY2_640x480, and get(vid, 'ReturnedColorSpace') shows what getsnapshot delivers. Stop and delete the object before recreating it with a different format.

Do machine-vision cameras appear in winvideo too?

No. winvideo lists USB Video Class devices, so GigE Vision and USB3 Vision cameras never show up there; they are acquired through the manufacturer SDK or a GenTL interface instead. When such a camera sends Bayer data, set ReturnedColorSpace to 'bayer' and the toolbox demosaics the pattern into RGB on each snapshot.