Skip to content

Code to create the squarest mosaic #3

@davidssmith

Description

@davidssmith

This is a very nice package.

A long, long time ago I wrote the code to tile images into a mosaic that was as square as possible. I don't have time to create a PR, so I'm offering the code here so that you can use the algorithm if you're interested. Maybe it could be a useful default?

function mosaic{T,N}(img::Array{T,N})
  # Create a 2-D mosaic of images from an n-D stack.
  # The first two dimensons are preserved and all additional
  # dimensions are lumped together as tiles
  imsize = size(img)
  n1 = imsize[1]
  n2 = imsize[2]
  n3 = prod(imsize[3:end])
  img = reshape(img, n1, n2, n3)
  n = int(round(sqrt(n3)))  # starting point: integer nearest to the square root
  # find largest integer less than or equal to sqrt that evenly divides the
  # number of images in the stack
  k = 0
  for k in n:-1:1
    if n3 % k == 0
      break
    end
  end
  # figure out the best dimensions
  j = int(n3 / k)
  ny = int(min(j, k))
  nx = int(max(j, k))
  # stick them together
  M = zeros(eltype(img), ny*n1, nx*n2)
  for k in 1:ny, j in 1:nx
    M[1 + n1*(k-1):n1*k, 1 + n2*(j-1):n2*j] = img[:, :, j+(k-1)*nx]
  end
  M
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions