---
title: "Convert RGB pixels to a CHW tensor in C#"
url: https://recursiveai.org/onemodel/cookbook/convert-rgb-pixels-to-chw-tensor/
description: "Convert raw RGB pixels to a float32 CHW tensor in C# with OneModel. Skip source row padding, normalize each channel, and print the red, green, and blue planes."
version: "1.3.0"
---

# Convert RGB pixels to a CHW tensor in C#

**OneModel** is a free, open-source neural-network library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel.Training) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/convert-rgb-pixels-to-chw-tensor/convert-rgb-pixels-to-chw-tensor.zip)

Use `Rgb8ToPlanar` to turn decoded RGB bytes into three float32 planes: red, green, then blue.

```shell
dotnet add package RecursiveAI.OneModel.Training
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System;
using RecursiveAI.OneModel.Tensors;
using RecursiveAI.OneModel.Training.Data;

// Two rows: RGB pixels, then 2 pad bytes.
byte[] rgb = [
    255, 0, 0, 0, 255, 0, 99, 99,
    0, 0, 255, 255, 255, 255, 99, 99];
var shape = Shape.Create(3, 2, 2);
using var chw =
    Tensor.Create(DType.F32, shape);
var data = chw.MutableData<float>();
ImageTensors.Rgb8ToPlanar(rgb, 2, 2, data,
    mean: [0.5f, 0.5f, 0.5f],
    std: [0.5f, 0.5f, 0.5f], stride: 8);
for (int c = 0; c < 3; c++)
{
    var plane = data.Slice(c * 4, 4);
    Console.WriteLine($"{"RGB"[c]}: " +
        string.Join(", ", plane.ToArray()));
}
```

Unzip [the example](https://recursiveai.org/onemodel/cookbook/convert-rgb-pixels-to-chw-tensor/convert-rgb-pixels-to-chw-tensor.zip), then `dotnet run`.

Prints:

```text
R: 1, -1, -1, 1
G: -1, 1, -1, 1
B: -1, -1, 1, 1
```

## The full program

The image helpers ship in the `RecursiveAI.OneModel.Training` package.

Each source row has six RGB bytes and two padding bytes (`99`). `stride: 8` tells OneModel where the next row starts. Each printed line is one plane of the `[3, 2, 2]` tensor in row order. `Rgb8ToPlanar` throws `ArgumentException` if the stride is shorter than a row or the pixel buffer is too short for the given layout.

```csharp
using System;
using RecursiveAI.OneModel.Tensors;
using RecursiveAI.OneModel.Training.Data;

// Two rows: RGB pixels, then 2 pad bytes.
byte[] rgb = [
    255, 0, 0, 0, 255, 0, 99, 99,
    0, 0, 255, 255, 255, 255, 99, 99];
var shape = Shape.Create(3, 2, 2);
using var chw =
    Tensor.Create(DType.F32, shape);
var data = chw.MutableData<float>();
ImageTensors.Rgb8ToPlanar(rgb, 2, 2, data,
    mean: [0.5f, 0.5f, 0.5f],
    std: [0.5f, 0.5f, 0.5f], stride: 8);
for (int c = 0; c < 3; c++)
{
    var plane = data.Slice(c * 4, 4);
    Console.WriteLine($"{"RGB"[c]}: " +
        string.Join(", ", plane.ToArray()));
}

Console.WriteLine($"Shape: {chw.Shape}");
```

Output from `dotnet run`:

```text
R: 1, -1, -1, 1
G: -1, 1, -1, 1
B: -1, -1, 1, 1
Shape: [3,2,2]
```

## Variations

### Scale to 0–1 without subtracting a mean

Replace the `Rgb8ToPlanar` call with this. Keep the same stride so the padding stays out of the result.

```csharp
ImageTensors.Rgb8ToPlanar(rgb, 2, 2, data, stride: 8);
```

The red plane now prints `R: 1, 0, 0, 1`.

## Related recipes

- [Slice and reshape tensor views](https://recursiveai.org/onemodel/cookbook/slice-and-reshape-tensor-views/)
- [Run an ONNX model in C#](https://recursiveai.org/onemodel/cookbook/run-onnx-model/)

## The short answer

Allocate a float32 `Tensor` with shape `[3, height, width]`. Pass its writable span and your decoded RGB8 buffer to `ImageTensors.Rgb8ToPlanar`. If rows have padding, pass the number of bytes between their starts as `stride`. Use the model’s expected normalization, not the sample’s values by default.

## What’s the difference between HWC and CHW for an RGB image?

HWC means height, width, channels. In an interleaved RGB buffer, the three bytes for one pixel sit next to one another: `R0, G0, B0, R1, G1, B1`. CHW means channels, height, width. In planar CHW memory, all the red values come first, followed by all green values, then all blue values. Each plane contains `height × width` values in row order. For a pixel at `(x, y)`, channel `c` sits at `c * height * width + y * width + x` in the destination.

Changing only the shape label doesn’t reorder the data. `Rgb8ToPlanar` reads the interleaved bytes and writes them in plane order while converting to float32. Check the receiving model’s layout: if it expects `[1, 3, H, W]` for a single image, the leading `1` is a batch dimension and doesn’t change the order of these values. If it expects channels last, this conversion doesn’t produce that layout.

## How do you handle row padding when converting RGB pixels to a tensor?

Use the source’s stride in **bytes**, not its width in pixels. Two RGB pixels use six bytes per row, but the sample stores the next row eight bytes after the first. Passing `stride: 8` skips the two padding bytes. Omitting the stride uses `width * 3`, which would read the padding as the first two components of the next row. Padding never needs to be added to the destination: the planes are tightly packed.

This is raw RGB8 preprocessing, not image decoding. To get RGB bytes from a PNG or JPEG, load the file with OneImage’s `Image.Load`, read `Width` and `Height`, and [pull pixels with `ToArray<Rgb24>()`](https://recursiveai.org/oneimage/docs/guide/#pixel-access-and-canvas). Copy each pixel’s `R`, `G`, and `B` bytes in that order into a contiguous buffer; these packed rows have a stride of `width * 3` bytes.

For an already packed RGB buffer, `Rgb8ToTensor` can allocate the CHW tensor itself; that helper doesn’t accept a custom stride. Use `Rgb8ToPlanar` with allocated storage for padded input.

## How do you normalize RGB channels for a model?

[OneModel’s image helpers](https://recursiveai.org/onemodel/docs/data-loading/) scale each byte to the 0–1 interval, subtract the channel’s `mean`, and divide by its `std`. Both arrays are in RGB order. Omitting them gives zero means and unit divisors, so you only get the 0–1 scaling. In the sample, a byte of `255` becomes `(1 − 0.5) / 0.5 = 1`, and `0` becomes `(0 − 0.5) / 0.5 = −1`. These sample values make the planes easy to read. For a real model, copy the normalization used when the model was trained.
