Determine if points are within ellipse (Python and Pillow) - python

Using PIL, I've drawn an ellipse using the square coordinates around the circle (ie, the X and Y coordinates of the shape if it were a square).
I want to determine if coordinates I pass in are within the range of the coordinates of the ellipse. If this were a square, I imagine this would be relatively easy, as I could simply ask the script to determine if the coordinates (x and y) are between the range of x and y coordinates of the square.
However, because it's an ellipse, I do not know the coordinates of the lines produced by the arc. For this reason, I believe I need a PIL solution to give me the range of the ellipse line first. Does this exist natively in PIL?

Full handwork solution incoming
Since an ellipse is just a "stuffed circle", one could resize the ellipse to be a circle and move on from there.
You have the coordinates, so the first step is to resize.
x_diff = abs(x_max - x_min)
x = (x - x_min ) / x_diff
y_diff = abs(y_max - y_min)
y = (y - y_min ) / y_diff
This resizes the ellipse to a circle with radius .5.
Using Pythagora's theorem, the distance to (0, 0) should be lower than the distances to the x and y axis, each squared. So a² + b² = c² becomes c <= sqrt(a² + b²). And since we have scaled the ellipse to a circle with radius 0.5, we can assume, that c has to be smaller or equal to 0.5.
import math
c = math.sqrt(x**2 + y**2)
if c <= .5:
print("Coordinate lies within ellipse!")
else:
print("Try again :(")

Related

How to access the inner and outer pixels of a circle ROI on an image?

I'm trying to solve a problem and am quite stuck on how to approach it. I have an image and I want to get all the pixels inside the circle area of interest.
The radius of the circle is 150 pixels and the centre point of the ROI is [256, 256].
I have tried to draw the circle on the image, but I couldn't find a way to access those pixels from that.
img = imread('Model/m1.png') * 255
row = size(img, 0) #imgWidth
col = size(img, 1) #imgHeight
px = row * col
circle = Circle((256, 256), 150, fill = False)
fig, ax = subplots()
ax.add_patch(circle)
imshow(img, cmap='gray')
show()
I was thinking maybe using the equation of a circle:
(x - a)**2 + (y - b)**2 == r**2
But I'm not quite sure as wouldn't that only give you the pixels of the circle edge?
Any ideas or tips would be much appreciated.
Inequality (x - a)**2 + (y - b)**2 <= r**2 allows to walk through all pixels inside circle.
In practice you can scan Y-coordinates from b-r to b+r and walk through horizontal lines of corresponding X-range a - sqrt(r**2 - (y-b)**2) .. a + sqrt(r**2 - (y-b)**2)

PyCairo : how to resize & rotate an image by its center to a final canvas

Using PyCairo, I want to be able to have a method that can put, resize & rotate a given ImageSurface on a context, but rotating by the center of the image (not the top-left)
Okay I've tried the examples I've found here but without any success.
Let's introduce the "context" in details.
I've got a "finale" ImageSurface (say A) on which some other images & texts are written.
I want to put on it another ImageSurface (say B), at a specified position where this position is the top-left where to put B on A. Then I need to resize B (reduce its size) and to rotate it by its center instead of by its top-left corner.
Here is an illustration of the wanted result :
I've tried the following but without success:
def draw_rotated_image(ctx, image_surface, left, top, width, height, angle):
ctx.save()
w = image_surface.get_width()
h = image_surface.get_height()
cl = left / (width/w)
ct = top / (height/h)
ctx.rotate(angle*3.1415927/180)
ctx.scale(width/w, height/h)
ctx.translate(cl + (-0.5*w),ct + (-0.5*h) )
ctx.set_source_surface(image_surface, 0, 0)
ctx.paint()
ctx.restore()
return
Thanks a lot for your help :)
Well, I finally made it ! (thanks to my 14 year old son who made me revise my trigonometry)
I'm trying to explain here my solution.
First, I AM NOT A MATHEMATICIAN. So there is probably a best way, and surely my explanation have errors, but I'm just explaining the logical way I have used to get the good result.
The best idea for that is to first draw a circle around the rectangle, because we need to move the top-left corner of this rectangle, around its own circle, according to the desired angle.
So to get the radius of the rectangle circle, we need to compute its hypothenuse, then to divide by 2 :
hypothenuse = math.hypot(layerWidth,layerHeight)
radius = hypothenuse / 2
Then we will be able to draw a circle around the rectangle.
Second, we need to know at which angle, on this circle, is the actual top-left corner of the rectangle.
So for that, we need compute the invert tangent of the rectangle, which is arc-tan(height/width).
But because we want to know how many degrees are we far from 0°, we need to compute the opposite so arc-tan(width/height).
Finally, another singularity is that Cairo 0° is in fact at 90°, so we will have to rotate again.
This can be shown by this simple graphic :
So finally, what is necessary to understand ?
If you want to draw a layer, with an angle, rotated by its center, the top-left point will move around the circle according to the desired angle.
The top-left position with a given angle of 0 needs to be "the reference".
So we need to get the new X-Y position where to start putting the layer to be able to rotate it :
Now, we can write a function that will return the X-Y pos of the top left rectangle where to draw it with a given angle :
def getTopLeftForRectangleAtAngle(layerLeft,layerTop,layerWidth,layerHeight,angleInDegrees):
# now we need to know the angle of the top-left corner
# for that, we need to compute the arc tangent of the triangle-rectangle:
layerAngleRad = math.atan((layerWidth / layerHeight))
layerAngle = math.degrees(layerAngleRad)
# 0° is 3 o'clock. So we need to rotate left to 90° first
# Then we want that 0° will be the top left corner which is "layerAngle" far from 0
if (angleInDegrees >= (90 + layerAngle)):
angleInDegrees -= (90 + layerAngle)
else:
angleInDegrees = 360 - ((90 + layerAngle) - angleInDegrees)
angle = (angleInDegrees * math.pi / 180.0)
centerLeft = layerLeft + (layerWidth / 2)
centerTop = layerTop + (layerHeight / 2)
# hypothenuse will help us knowing the circle radius
hypothenuse = math.hypot(layerWidth,layerHeight)
radius = hypothenuse / 2
pointX = centerLeft + radius * math.cos(angle)
pointY = centerTop + radius * math.sin(angle)
return (pointX,pointY)
And finally, here is how to use it with an image we want to resize, rotate and write on a context:
def draw_rotated_image(ctx, image_surface, left, top, width, height, angle=0.0, alpha=1.0):
ctx.save()
w = image_surface.get_width()
h = image_surface.get_height()
# get the new top-left position according to the given angle
newTopLeft = getTopLeftForRectangleAtAngle(left, top, width, height, angle)
# translate
ctx.translate(newTopLeft[0], newTopLeft[1])
# rotate
ctx.rotate(angle * math.pi / 180)
# scale & write
ctx.scale(width/w, height/h)
ctx.set_source_surface(image_surface, 0, 0)
ctx.paint_with_alpha(alpha)
ctx.restore()
return

For (x, y) pixel coordinates in length of line, adjust angle to become circle

I have have a function to generate pixel coordinates of a line of a given angle and pixel length.
# Start position of line
lineStartX = 100
lineStartY = 100
# Length of line in pixels
lineLength = 100
# Set angle of line
angle = 0
for pixel in range(lineLength):
# Next pixel with angle adjustment
endy = (pixel + 1) * math.sin(math.radians(angle))
endx = (pixel + 1) * math.cos(math.radians(angle))
# Add next pixel with angle adjustment to line start coordinates
Xcoordinate = lineStartX + (endx)
Ycoordinate = lineStartY + (endy)
How can i adjust the angle of each concurrent pixel coordinate to form a circle?
I've tried adjusting the angle incrementally for each pixel but it only partially completes the circle, I'm not sure what to do next.
angle += 0.10
Update: When i increment the angle as suggested:
angle += 2 * np.arcsin(math.pi / lineLength)
The circle still only partially completes
Should the line be a circle, the length equal would its circumference.
Since drawing a perfect circle on a pixel matrix is not possible, some approximation rules will be in order. You could try incrementally adjusting the angle not by 0.10 but by
2 * arcsin(pi / length)
to make the spiral's ends meet :)

How can I create a circular mask for a numpy array?

I am trying to circular mask an image in Python. I found some example code on the web, but I'm not sure how to change the maths to get my circle in the correct place.
I have an image image_data of type numpy.ndarray with shape (3725, 4797, 3):
total_rows, total_cols, total_layers = image_data.shape
X, Y = np.ogrid[:total_rows, :total_cols]
center_row, center_col = total_rows/2, total_cols/2
dist_from_center = (X - total_rows)**2 + (Y - total_cols)**2
radius = (total_rows/2)**2
circular_mask = (dist_from_center > radius)
I see that this code applies euclidean distance to calculate dist_from_center, but I don't understand the X - total_rows and Y - total_cols part. This produces a mask that is a quarter of a circle, centered on the top-left of the image.
What role are X and Y playing on the circle? And how can I modify this code to produce a mask that is centered somewhere else in the image instead?
The algorithm you got online is partly wrong, at least for your purposes. If we have the following image, we want it masked like so:
The easiest way to create a mask like this is how your algorithm goes about it, but it's not presented in the way that you want, nor does it give you the ability to modify it in an easy way. What we need to do is look at the coordinates for each pixel in the image, and get a true/false value for whether or not that pixel is within the radius. For example, here's a zoomed in picture showing the circle radius and the pixels that were strictly within that radius:
Now, to figure out which pixels lie inside the circle, we'll need the indices of each pixel in the image. The function np.ogrid() gives two vectors, each containing the pixel locations (or indices): there's a column vector for the column indices and a row vector for the row indices:
>>> np.ogrid[:4,:5]
[array([[0],
[1],
[2],
[3]]), array([[0, 1, 2, 3, 4]])]
This format is useful for broadcasting so that if we use them in certain functions, it will actually create a grid of all the indices instead of just those two vectors. We can thus use np.ogrid() to create the indices (or pixel coordinates) of the image, and then check each pixel coordinate to see if it's inside or outside the circle. In order to tell whether it's inside the center, we can simply find the Euclidean distance from the center to every pixel location, and then if that distance is less than the circle radius, we'll mark that as included in the mask, and if it's greater than that, we'll exclude it from the mask.
Now we've got everything we need to make a function that creates this mask. Furthermore we'll add a little bit of nice functionality to it; we can send in the center and the radius, or have it automatically calculate them.
def create_circular_mask(h, w, center=None, radius=None):
if center is None: # use the middle of the image
center = (int(w/2), int(h/2))
if radius is None: # use the smallest distance between the center and image walls
radius = min(center[0], center[1], w-center[0], h-center[1])
Y, X = np.ogrid[:h, :w]
dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
mask = dist_from_center <= radius
return mask
In this case, dist_from_center is a matrix the same height and width that is specified. It broadcasts the column and row index vectors into a matrix, where the value at each location is the distance from the center. If we were to visualize this matrix as an image (scaling it into the proper range), then it would be a gradient radiating from the center we specify:
So when we compare it to radius, it's identical to thresholding this gradient image.
Note that the final mask is a matrix of booleans; True if that location is within the radius from the specified center, False otherwise. So we can then use this mask as an indicator for a region of pixels we care about, or we can take the opposite of that boolean (~ in numpy) to select the pixels outside that region. So using this function to color pixels outside the circle black, like I did up at the top of this post, is as simple as:
h, w = img.shape[:2]
mask = create_circular_mask(h, w)
masked_img = img.copy()
masked_img[~mask] = 0
But if we wanted to create a circular mask at a different point than the center, we could specify it (note that the function is expecting the center coordinates in x, y order, not the indexing row, col = y, x order):
center = (int(w/4), int(h/4))
mask = create_circular_mask(h, w, center=center)
Which, since we're not giving a radius, would give us the largest radius so that the circle would still fit in the image bounds:
Or we could let it calculate the center but use a specified radius:
radius = h/4
mask = create_circular_mask(h, w, radius=radius)
Giving us a centered circle with a radius that doesn't extend exactly to the smallest dimension:
And finally, we could specify any radius and center we wanted, including a radius that extends outside the image bounds (and the center can even be outside the image bounds!):
center = (int(w/4), int(h/4))
radius = h/2
mask = create_circular_mask(h, w, center=center, radius=radius)
What the algorithm you found online does is equivalent to setting the center to (0, 0) and setting the radius to h:
mask = create_circular_mask(h, w, center=(0, 0), radius=h)
I'd like to offer a way to do this that doesn't involve the np.ogrid() function. I'll crop an image called "robot.jpg", which is 491 x 491 pixels. For readability I'm not going to define as many variables as I would in a real program:
Import libraries:
import matplotlib.pyplot as plt
from matplotlib import image
import numpy as np
Import the image, which I'll call "z". This is a color image so I'm also pulling out just a single color channel. Following that, I'll display it:
z = image.imread('robot.jpg')
z = z[:,:,1]
zimg = plt.imshow(z,cmap="gray")
plt.show()
robot.jpg as displayed by matplotlib.pyplot
To wind up with a numpy array (image matrix) with a circle in it to use as a mask, I'm going to start with this:
x = np.linspace(-10, 10, 491)
y = np.linspace(-10, 10, 491)
x, y = np.meshgrid(x, y)
x_0 = -3
y_0 = -6
mask = np.sqrt((x-x_0)**2+(y-y_0)**2)
Note the equation of a circle on that last line, where x_0 and y_0 are defining the center point of the circle in a grid which is 491 elements tall and wide. Because I defined the grid to go from -10 to 10 in both x and y, it is within that system of units that x_0 and x_y set the center point of the circle with respect to the center of the image.
To see what that produces I run:
maskimg = plt.imshow(mask,cmap="gray")
plt.show()
Our "proto" masking circle
To turn that into an actual binary-valued mask, I'm just going to take every pixel below a certain value and set it to 0, and take every pixel above a certain value and set it to 256. The "certain value" will determine the radius of the circle in the same units defined above, so I'll call that 'r'. Here I'll set 'r' to something and then loop through every pixel in the mask to determine if it should be "on" or "off":
r = 7
for x in range(0,490):
for y in range(0,490):
if mask[x,y] < r:
mask[x,y] = 0
elif mask[x,y] >= r:
mask[x,y] = 256
maskimg = plt.imshow(mask,cmap="gray")
plt.show()
The mask
Now I'll just multiply the mask by the image element-wise, then display the result:
z_masked = np.multiply(z,mask)
zimg_masked = plt.imshow(z_masked,cmap="gray")
plt.show()
To invert the mask I can just swap the 0 and the 256 in the thresholding loop above, and if I do that I get:
Masked version of robot.jpg
The other answers work, but they are slow, so I will propose an answer using skimage.draw.disk. Using this is faster and I find it simple to use. Simply specify the center of the circle and radius then use the output to create a mask
from skimage.draw import disk
mask = np.zeros((10, 10), dtype=np.uint8)
row = 4
col = 5
radius = 5
rr, cc = disk(row, col, radius)
mask[rr, cc] = 1

Draw precise circle through two points

I am programming an application for high precision measurements. Now I have a problem.
User can select a segment on axis X that would represent diameter of a circle.
How do I draw the circle in question through two selected end points if the selected diameter has even pixel length
In this case origin of the circle would be between two pixels, which would make me choose one of them, thus shifting the circle one pixel left or right.
It is true, the look wouldn't change because one pixel will be included and another added on the other side of selected segment, but what if I need to draw a square based on the segment's length around the area first.
Then circle and square would touch in wrong places.
What is usually done in this circumstances?
ImageDraw.Draw.ellipse takes a bounding box as a parameter. It doesn't care where the center of the circle goes.
The circle outline includes all 4 edges of the bounding box in the tests I performed. I suggest you do your own tests too.
Calculating the bounding box from two arbitrary points is easy, once you have the diameter and center of the circle.
diameter = ((x2 - x1)**2 + (y2 - y1)**2) ** 0.5
radius = diameter / 2
xC, yC = (x1 + x2) / 2.0, (y1 + y2) / 2.0
bbox = [round(xC - radius), round(yC - radius), round(xC + radius), round(yC + radius)]

Categories