using Clustering, Images, ColorSchemes
using Plots
plotlyjs()
function image2zvals(img::Union{Matrix{RGB{T}}, Matrix{RGBA{T}}};
n_colors=64, maxiter=200, tol=1e-04) where T<:Real
rows, cols = size(img)
observations = reshape(img, rows*cols)
kmres = kmeans(observations, n_colors; maxiter = maxiter, tol=tol)
nclust = nclusters(kmres)
a = assignments(kmres)/nclust
z_data = reshape(a, rows, cols)
hcolors = kmres.centers # kmres.centers is the codebook
if fieldcount(eltype(img)) == 3
cscheme = ColorScheme([RGB(c...) for c in eachcol(hcolors)])
else
cscheme = ColorScheme([RGB(c[1:3]...) for c in eachcol(hcolors)])
end
return z_data, cscheme
end
The WebIO Jupyter extension was not detected. See the WebIO Jupyter integration documentation for more information.
image2zvals (generic function with 1 method)
img = load("heatmap-forum.jpeg");
zdata, cscheme = image2zvals(img; n_colors=64, maxiter=200, tol=1e-04);
Reconstructed heatmap:
plt = heatmap(zdata[end:-1:1,:], c=cgrad(cscheme), cbar=false, size=(375, 300))
zdata
240×320 Matrix{Float64}: 0.0625 0.0625 0.0625 0.0625 … 0.84375 0.828125 0.9375 0.0625 0.0625 0.0625 0.0625 0.234375 0.8125 0.9375 0.0625 0.0625 0.0625 0.0625 0.828125 0.0625 0.59375 0.0625 0.0625 0.0625 0.0625 0.828125 0.59375 0.0625 0.0625 0.0625 0.0625 0.0625 0.328125 0.328125 0.828125 0.0625 0.0625 0.0625 0.0625 … 0.734375 0.328125 0.828125 0.0625 0.0625 0.0625 0.0625 0.59375 0.0625 0.59375 0.0625 0.0625 0.0625 0.0625 0.703125 0.859375 0.9375 0.0625 0.0625 0.0625 0.0625 0.703125 0.9375 0.9375 0.8125 0.8125 0.0625 0.0625 0.703125 0.9375 0.0625 0.8125 0.8125 0.8125 0.0625 … 0.0625 0.59375 0.0625 0.8125 0.8125 0.8125 0.0625 0.0625 0.59375 0.0625 0.8125 0.8125 0.0625 0.8125 0.9375 0.59375 0.0625 ⋮ ⋱ 0.703125 0.859375 0.859375 0.34375 0.453125 0.15625 0.421875 0.859375 0.859375 0.59375 0.828125 0.359375 0.453125 0.453125 0.703125 0.859375 0.703125 0.59375 … 0.421875 0.453125 0.3125 0.859375 0.859375 0.859375 0.859375 0.421875 0.359375 0.40625 0.59375 0.59375 0.8125 0.8125 0.90625 0.453125 0.3125 0.59375 0.34375 0.8125 0.328125 0.453125 0.359375 0.109375 0.59375 0.59375 0.34375 0.59375 0.3125 0.453125 0.359375 0.859375 0.859375 0.34375 0.59375 … 0.890625 0.3125 0.453125 0.859375 0.859375 0.859375 0.859375 0.578125 0.890625 0.890625 0.859375 0.859375 0.859375 0.859375 0.671875 0.671875 0.671875 0.859375 0.859375 0.859375 0.859375 0.40625 0.890625 0.890625 0.859375 0.859375 0.859375 0.859375 0.3125 0.40625 0.671875
.
.