Skip to content

Fix image shape calculation in ToTensor method#90

Open
ncguilbeault wants to merge 1 commit into
bonsai-rx:mainfrom
ncguilbeault:ng-dev/fix-image-shape
Open

Fix image shape calculation in ToTensor method#90
ncguilbeault wants to merge 1 commit into
bonsai-rx:mainfrom
ncguilbeault:ng-dev/fix-image-shape

Conversation

@ncguilbeault

Copy link
Copy Markdown
Collaborator

This PR fixes how the ToTensor method in the Bonsai.ML.Torch package computes the width of a tensor converted from an IplImage. Previously, the width was derived by dividing WidthStep by the number of channels. However, since WidthStep is the row stride in bytes, this calculation is only correct for images with 1-byte element types (U8/S8). For images with wider element types (S16, S32, F32, F64), the computed width was inflated by the element size in bytes, producing a tensor with an incorrect shape that describes more memory than the underlying image buffer actually contains.

This PR changes the calculation to first convert the byte stride into an element stride, by dividing WidthStep by the element size of the input image data type, before dividing by the number of channels. The tensor dimensions are now correctly mapped to the image's data for all supported bit depths, and the resulting tensor no longer overruns the backing buffer.

Fixes #88.

@ncguilbeault ncguilbeault requested a review from glopesdev July 13, 2026 16:06
@ncguilbeault ncguilbeault added bug Something isn't working fix Pull request that fixes an issue labels Jul 13, 2026
@ncguilbeault ncguilbeault added this to the v0.5.0 milestone Jul 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working fix Pull request that fixes an issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ToTensor(IplImage) computes incorrect width for non-8-bit images (WidthStep not divided by element size)

1 participant