Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project a circle onto a square?

I have an photograph of a retina stored as a numpy array. I'll represent this image with this 2D numpy array (my actual array is much bigger, has 3 color channels and the values are floats, not all 0 or 1):

array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0]])

How can I project the circle (stretch the edges somehow?) so that it becomes a square without getting cropped? So that it looks like this:

array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0]])

Basically, I'm looking for a Python library that can do the conformal mapping in this image

conformal mapping from circle to square

like image 974
Boris Avatar asked Nov 09 '22 11:11

Boris


1 Answers

Use squircle for this (disclaimer: I wrote it)

import squircle
import PIL
import numpy as np

square = np.asarray(Image.open('some-square-image.jpg'))  # or create the array some other way

circle = squircle.to_circle(square, method="fgs")
and_back_to_square = squircle.to_square(circle, method="fgs")

there's 3 different methods for transforming circles/squares: "fgs", "stretch" and "elliptical"

It doesn't handle ellipses and rectangles, but you can do that by upsampling the image, naively squishing it into a square, running squircle on it and unsquishing it back into a rectangle.

You can install it with

pip install squircle
like image 58
Boris Avatar answered Nov 14 '22 22:11

Boris