Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting images from array containing datatype UInt8

Tags:

julia

plots.jl

I have a bunch of images (of cats) and want to plot one of them. The values image are in the format UInt8 and contain 3 bands. When I try to plot using plots I get the following error, ERROR: StackOverflowError.

 Using Plots

# Get data
train_data_x = fid["train_set_x"] |> HDF5.read
#Out >
3×64×64×209 Array{UInt8, 4}:
[:, :, 1, 1] =
0x11  0x16  0x19  0x19  0x1b  …  0x01  0x01  0x01  0x01
0x1f  0x21  0x23  0x23  0x24     0x1c  0x1c  0x1a  0x16
0x38  0x3b  0x3e  0x3e  0x40     0x3a  0x39  0x38  0x33
...

# Reshape to be in the format, no_of_images x length x width x channels
train_data_rsp = reshape(train_data_x, (209,64,64,3))

# Get first image 
first_img = train_data_rsp[1, :, :, :]

plot(first_img)
Out >
ERROR: StackOverflowError:

# I also tried plotting one band and I get a line plot
plot(train_data_rsp[1,:,:,1])
#Out >

enter image description here

Any ideas whats incorrect with my code?

like image 974
imantha Avatar asked May 16 '26 02:05

imantha


1 Answers

First, I'd be careful about how you're reshapeing; I think this will merely rearrange the pixels in your images instead of swapping the dimensions, which it seems like you want to do. You may want train_data_rsp = permutedims(train_data_x, (4, 2, 3, 1)) which will actually swap the dimensions around and give you a 209×64×64×3 array with the semantics of which pixels belong to which images preserved.

Then, Julia's Images package has a colorview function that lets you combine the separate R,G,B channels into a single image. You'll first need to convert your array element type into N0f8 (a single-byte format where 0 corresponds to 0 and 255 to 1) so that Images can work with it. It would look something like this:

julia> arr_rgb = N0f8.(first_img // 255)  # rescale UInt8 in range [0,255] to Rational with denominator 255 in range [0,1]
64×64×3 Array{N0f8,3} with eltype N0f8:
[...]
julia> img = colorview(RGB, map(i->selectdim(arr_rgb, 3, i), 1:3)...)
64×64 mappedarray(RGB{N0f8}, ImageCore.extractchannels, view(::Array{N0f8,3}, :, :, 1), view(::Array{N0f8,3}, :, :, 2), view(::Array{N0f8,3}, :, :, 3)) with eltype RGB{N0f8}:
[...]

Then you should be able to plot this image.

like image 141
BallpointBen Avatar answered May 19 '26 04:05

BallpointBen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!