# Automatic Threshold image

**URL:** <https://discourse.julialang.org/t/automatic-threshold-image/25028>\
**Category:** General Usage\
**Created:** [June 6, 2019, 10:07pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028 "2019-06-06T22:07:44Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 6, 2019, 10:07pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/1 "2019-06-06T22:07:44Z")

</div>

How can I do the process …

This is my code.  
I’m working in Juno.

using ImageContrastAdjustment, Images, ImageFiltering, TestImages, ColorTypes, HistogramThresholding  
const ICA = ImageContrastAdjustment

function example()  
img = testimage(“circulo”)

```
# Grayscale image.
imgg = Gray.(img)

# Linear contrast stretching.
imggₗ = ICA.adjust_histogram(ICA.LinearStretching(), imgg)

# Histogram Equalization.
imggₑ = ICA.adjust_histogram(ICA.Equalization(), imgg)

#=
   admiminsion and subtracion
 =#
R₁ = float.(imggₗ) + float.(imggₑ)

R₂ = R₁ - float.(imggₑ)

# imggₗ + imggₗ + imggₑ.
R₃ = R₁ + R₂

# Applying a minimum filter.
window_size = (-1:1, -1:1)
imgmin = mapwindow(minimum, R₃, window_size)

# divide el intervalo del valor más pequeño al más grande en imgmin en 256 bin
edges, counts = ICA.build_histogram(imgmin, 256, minval = minimum(imgmin), maxval = maximum(imgmin))

#=
La matriz `count` almacena en el índice 0 las frecuencias que estaban por debajo de
  primer borde del cubo. Ya que estamos buscando un umbral sobre el intervalo
  divididos por `edges` necesitamos descartar la primera bandeja en` count`
  de modo que las dimensiones de `edge` y` count` coincidan.
=#
t = find_threshold(Otsu(), counts[1:end], edges)

# Aplica el umbral a imgmin y checo el resultado.
img₀₁ = zeros(Gray{Bool}, axes(imgmin))
for i in CartesianIndices(img)
    img₀₁[i] = imgmin[i] < t ? 0 : 1
end
display(img₀₁)

```

end

example()

as a result I get this

 ![circule](https://global.discourse-cdn.com/julialang/original/3X/f/3/f36bd0b8e05afa6e5426e62a16584bb6aebd1610.png)

I need the white part to turn black and the black part to turn white.

this is my original image…

 ![20](https://global.discourse-cdn.com/julialang/original/3X/c/a/ca478e0495caaf417a655dec8770d1421c98f1be.jpeg)

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [June 7, 2019, 5:15am UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/2 "2019-06-07T05:15:48Z")

</div>

Possibly exchange the `0` and the `1` in

```julia
for i in CartesianIndices(img)
    img₀₁[i] = imgmin[i] < t ? 0 : 1
end

```

Or just use

```julia
for i in CartesianIndices(img)
    img₀₁[i] = imgmin[i] < t
end

```

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [June 7, 2019, 5:41am UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/3 "2019-06-07T05:41:40Z")

</div>

How about `imgmin .< t` or `.!(imgmin .< t)` alt. `imgmin .≮ t` to invert

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 3:36am UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/4 "2019-06-08T03:36:57Z")

</div>

How could you define the range in admission and subtraction over an image?

enter (0-255) without going past 255 or reducing me from 0.

my code is something like this …

```julia
#=
admiminsion and subtracion
=#
R₁ = float.(imggₗ) + float.(imggₑ)

R₂ = R₁ - float.(imggₑ)

# imggₗ + imggₗ + imggₑ.
R₃ = R₁ + R₂

```

but there the error is that I’m taking float values …

how could I do it to establish the range (0-255).

help me…!

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [June 8, 2019, 4:44pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/5 "2019-06-08T16:44:17Z")

</div>

> [@GERSON\_EZEQUIEL\_HERN](#):
>
> how could I do it to establish the range (0-255).

`clamp`

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 5:26pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/6 "2019-06-08T17:26:27Z")

</div>

if … without using float … because with float it is an error to the procedure, and so with float you can not enter whole values to put the range (0-255).

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 5:38pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/7 "2019-06-08T17:38:10Z")

</div>

and how do I use clamp

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 5:43pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/8 "2019-06-08T17:43:00Z")

</div>

this correct

```
#=
   admiminsion and subtracion
 =#
R₁ = clamp(0,255).(imggₗ) + clamp(0,255).(imggₑ)

R₂ = R₁ - clamp(0,255).(imggₑ)

# imggₗ + imggₗ + imggₑ.
R₃ = R₁ + R₂

```

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [June 8, 2019, 8:36pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/9 "2019-06-08T20:36:40Z")

</div>

`clamp` does not know how work directly on the image pixel type you use.  
You would have to overload `clamp` or translate to a numeric array, clamp that, and translate back to an image array. Note that clamping to 0…255 may mean clamping values 0.0…1.0 or some other range depending upon the representation of your image’s colorant/greyscale.

this is the online help for clamp

```julia
help?> clamp
search: clamp clamp!

  clamp(x, lo, hi)

  Return x if lo <= x <= hi. If x > hi, return hi. If x < lo, return lo. Arguments are promoted to a common
  type.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> clamp.([pi, 1.0, big(10.)], 2., 9.)
  3-element Array{BigFloat,1}:
   3.141592653589793238462643383279502884197169399375105820974944592307816406286198
   2.0
   9.0

  julia> clamp.([11,8,5],10,6) # an example where lo > hi
  3-element Array{Int64,1}:
    6
    6
   10

```

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 8:54pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/10 "2019-06-08T20:54:10Z")

</div>

and how can I use cleap in my code … using the range (0-255) without overflowing.

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 8, 2019, 8:57pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/11 "2019-06-08T20:57:26Z")

</div>

![Captura%20de%20pantalla%20(2)](https://global.discourse-cdn.com/julialang/original/3X/2/7/27ca493911be2b46ce6ad52209cd4d7049d1457c.png)

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [June 8, 2019, 9:31pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/13 "2019-06-08T21:31:29Z")

</div>

Also

you can just write

```julia
stretch = ICA.adjust_histogram(ICA.LinearStretching(), imgg)
adjust = ICA.adjust_histogram(ICA.Equalization(), imgg)
r3 = 2*stretch + adjust

```

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [June 8, 2019, 9:49pm UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/14 "2019-06-08T21:49:13Z")

</div>

This works.

```julia
using Images, ImageView, ImageContrastAdjustment, HistogramThresholding, TestImages

const ICA = ImageContrastAdjustment

img = testimage("lake_color") # change this to the image file you are using

# Grayscale image.
imgg = Gray.(img)

# Linear contrast stretching.
imggₗ = ICA.adjust_histogram(ICA.LinearStretching(), imgg)

# Histogram Equalization.
imggₑ = ICA.adjust_histogram(ICA.Equalization(), imgg)

#=
   admiminsion and subtracion
=#
R₃ = imggₗ + imggₗ + imggₑ

# Applying a minimum filter
window_size = (-1:1, -1:1)
imgmin = mapwindow(minimum, R₃, window_size)

# divide el intervalo del valor más pequeño al más grande en imgmin en 256 bin
edges, counts = ICA.build_histogram(imgmin, 256, 
                     minval = minimum(imgmin), maxval = maximum(imgmin))

#=
La matriz `count` almacena en el índice 0 las frecuencias que estaban por debajo de
  primer borde del cubo. Ya que estamos buscando un umbral sobre el intervalo
  divididos por `edges` necesitamos descartar la primera bandeja en` count`
  de modo que las dimensiones de `edge` y` count` coincidan.
=#
t = find_threshold(Otsu(), counts[1:end], edges)

# Aplica el umbral a imgmin y checo el resultado.
img₀₁ = zeros(Gray{Bool}, axes(imgmin))
for i in CartesianIndices(img)
   img₀₁[i] = imgmin[i] < t
end

imshow(img₀₁)

```

you can put it in a function

```julia
using Images, ImageView, ImageContrastAdjustment, HistogramThresholding, TestImages

const ICA = ImageContrastAdjustment

function example()
	img = testimage("lake_color") # change this to the image file you are using

	# Grayscale image.
	imgg = Gray.(img)

	# Linear contrast stretching.
	imggₗ = ICA.adjust_histogram(ICA.LinearStretching(), imgg)

	# Histogram Equalization.
	imggₑ = ICA.adjust_histogram(ICA.Equalization(), imgg)

	#=
	   admiminsion and subtracion
	=#
	R₃ = imggₗ + imggₗ + imggₑ

	# Applying a minimum filter
	window_size = (-1:1, -1:1)
	imgmin = mapwindow(minimum, R₃, window_size)

	# divide el intervalo del valor más pequeño al más grande en imgmin en 256 bin
	edges, counts = ICA.build_histogram(imgmin, 256, 
	                     minval = minimum(imgmin), maxval = maximum(imgmin))

	#=
	La matriz `count` almacena en el índice 0 las frecuencias que estaban por debajo de
	  primer borde del cubo. Ya que estamos buscando un umbral sobre el intervalo
	  divididos por `edges` necesitamos descartar la primera bandeja en` count`
	  de modo que las dimensiones de `edge` y` count` coincidan.
	=#
	t = find_threshold(Otsu(), counts[1:end], edges)

	# Aplica el umbral a imgmin y checo el resultado.
	img₀₁ = zeros(Gray{Bool}, axes(imgmin))
	for i in CartesianIndices(img)
	   img₀₁[i] = imgmin[i] < t
	end

	imshow(img₀₁)
end

example()

```

---

<div class="post-metadata">

**Author:** ![GERSON\_EZEQUIEL\_HERN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gerson_ezequiel_hern/32/7437_2.png) [@GERSON\_EZEQUIEL\_HERN](https://discourse.julialang.org/u/GERSON_EZEQUIEL_HERN)\
**Post date:** [June 9, 2019, 1:43am UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/15 "2019-06-09T01:43:55Z")

</div>

Sorry friend, a question …

(Maybe it sounds silly)

and where are you establishing the range between (0-255) of the process?

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [June 9, 2019, 2:50am UTC](https://discourse.julialang.org/t/automatic-threshold-image/25028/16 "2019-06-09T02:50:09Z")

</div>

Why do you think that the Gray pixel values can be outside of that range?

```julia
julia> typeof(R₃)
Array{Gray{Normed{UInt8,8}},2}

```

The `UInt8` there means that, internally, pixel values can range from `typemin(UInt8)` to `typemax(UInt8)`

```julia
julia> Int(typemin(UInt8)), Int(typemax(UInt8))
(0, 255)

```

The `Normed` means the values are normalized floats in the range [0.0, 1.0].  
Maybe you have some unusual image format or you use some other `Gray`er or the the image may have been tampered. You can force the matter this way

```julia
function clampgray(im::AbstractArray)
    gray = Gray.(im)
    T = typeof(gray)
    gray = T(map(x->clamp(x, 0.0, 1.0), gray))
    return gray
end
   
# and replace 
# imgg = Gray.(img)
# with
imgg = clampgray(img)

```

if you are really concerned … or just want to see `255` (UInt(255) == 0xff):

```julia
clampgraypixel(pixel) =
    N0f8(clamp(x.val.i, 0x00, 0xff) / 0xff)
    
function clampgray(im::AbstractArray)
    gray = Gray.(im)
    T = typeof(gray)
    gray = T(map(pixel->clampgraypixel(pixel), imgg)))
    return gray
end

```
