Ankur Sharma
Ankur Sharma

Reputation: 55

How to save {UINT16, 2} array to image in Julia

I have an Array{UInt16,2} in Julia of size 5328×3040. I want to save it to a png image.

I tried the following:

save("gray.png", colorview(Gray, img))

But got the following error:

ERROR: TypeError: in Gray, in T, expected T<:Union{Bool, AbstractFloat, FixedPoint}, got Type{UInt16}
Stacktrace:
 [1] ccolor_number at C:\Users\ankushar\.julia\packages\ImageCore\KbJyT\src\convert_reinterpret.jl:60 [inlined]
 [2] ccolor_number at C:\Users\ankushar\.julia\packages\ImageCore\KbJyT\src\convert_reinterpret.jl:57 [inlined]
 [3] colorview(::Type{Gray}, ::Array{UInt16,2}) at C:\Users\ankushar\.julia\packages\ImageCore\KbJyT\src\colorchannels.jl:104
 [4] top-level scope at REPL[16]:1
caused by [exception 3]
IOError: symlink: operation not permitted (EPERM)

I am using Julia 1.4.2

Can you suggest a good way to store these arrays as images in Julia?

TIA!

Upvotes: 4

Views: 707

Answers (2)

Oscar Smith
Oscar Smith

Reputation: 6378

A faster and more accurate solution is to reinterpret your array as an array of N0f16 which is a type from FixedPointNumbers which is basically just a Uint16 scaled between 0 and 1. This will both avoid rounding errors, but also prevent the need for making a copy.

using FixedPointNumbers

img = rand(UInt16, 10, 20)
colorview(Gray, reinterpret(N0f16, img)))

Upvotes: 1

daycaster
daycaster

Reputation: 2697

You can normalize the pixel values before saving.

using Images

img = rand(UInt16, 10, 20)

img[1:3]

# => 3-element Array{UInt16,1}:
 0x7fc2
 0x057e
 0xae79

gimg = colorview(Gray, img ./ typemax(UInt16))

gimg[1:3] |> channelview

# => 3-element reinterpret(Float64, ::Array{Gray{Float64},1}):
 0.4990615701533532
 0.02145418478675517
 0.6815442130159457

save("gray.png", gimg)

image

Upvotes: 2

Related Questions