dolam
dolam

Reputation: 21

julia-lang - Convert image to black and white

I'm trying to transform an image to black & white using Julia with threshold is 0.5. I've converted the image to grayscale, but not sure if that helps. I'm new to Julia so any help would be appreciated.

Upvotes: 1

Views: 987

Answers (2)

AVA
AVA

Reputation: 2558

try with the following code snippet:

using Images, ImageView;

function show_binary_image(img_path::String, threshold::Float16)
    img_binary = load(img_path);
    img_binary = (Gray.(img_binary) .> threshold);
    imshow(img_binary);
end

show_binary_image("/path/to/image/file", convert(Float16, 0.5));

Upvotes: 1

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

Can you please provide an example of your input and the specification of desired output? In general if x is a matrix of Float64 containing your gray scale image then Float64.(x .> 0.5) will give you what you want. For example:

julia> img = rand(5,4)
5×4 Array{Float64,2}:
 0.294821  0.719161   0.36838    0.0962881
 0.262626  0.0169155  0.7068     0.668797
 0.450861  0.493318   0.0125666  0.783241
 0.267667  0.652534   0.0860362  0.811446
 0.586622  0.08407    0.316635   0.36396

julia> Float64.(img .> 0.5)
5×4 Array{Float64,2}:
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  1.0
 0.0  0.0  0.0  1.0
 0.0  1.0  0.0  1.0
 1.0  0.0  0.0  0.0

If you wanted to specify explicitly target values (the code above uses the fact that true gets converted to 1.0 and false to 0.0) you can write:

julia> ifelse.(img .> 0.5, 1.0, 0.0)
5×4 Array{Float64,2}:
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  1.0
 0.0  0.0  0.0  1.0
 0.0  1.0  0.0  1.0
 1.0  0.0  0.0  0.0

You can achieve this result also using comprehensions:

julia> Float64[v > 0.5 for v in img]
5×4 Array{Float64,2}:
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  1.0
 0.0  0.0  0.0  1.0
 0.0  1.0  0.0  1.0
 1.0  0.0  0.0  0.0

julia> [ifelse(v > 0.5, 1.0, 0.0) for v in img]
5×4 Array{Float64,2}:
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  1.0
 0.0  0.0  0.0  1.0
 0.0  1.0  0.0  1.0
 1.0  0.0  0.0  0.0

Upvotes: 2

Related Questions