In my app I am currently able to work out whether the user's tap is within a rectangular area simply by checking all of the following conditions are true:
Finger X > rectangle X
Finger Y > rectangle Y
Finger X < rectangle X + rectangle Width
Finger Y < rectangle Y + rectangle Height
However, I now have to determine if the user taps within a circular area. Currently I have a circular shape on screen and have resorted to just checking it's bounding rectangle, which works but obviously isn't great.
Any help would be appreciated.
The distance between two points in two dimensions is defined as
dist = sqrt((x2-x1)^2 + (y2-y1)^2)
To check if your tap point is inside a circle, take the centre of your circle as (x1,y1), and the 'tap location' as (x2,y2), and check if
sqrt((x2-x1)^2 + (y2-y1)^2) < R
With R being the radius of your circle.
Edit:
As John mentioned, from a computational point of view it is more interesting to compare vs R^2, to avoid the sqrt for every tap. So the condition becomes:
(x2-x1)^2 + (y2-y1)^2 < R^2
Related
I am trying to find the direction of triangles in an image. below is the image:
These triangles are pointing upward/downward/leftward/rightward. This is not the actual image. I have already used canny edge detection to find edges then contours and then the dilated image is shown below.
My logic to find the direction:
The logic I am thinking to use is that among the three corner coordinates If I can identify the base coordinates of the triangle (having the same abscissa or ordinates values coordinates), I can make a base vector. Then angle between unit vectors and base vectors can be used to identify the direction. But this method can only determine if it is up/down or left/right but cannot differentiate between up and down or right and left. I tried to find the corners using cv2.goodFeaturesToTrack but as I know it's giving only the 3 most effective points in the entire image. So I am wondering if there is other way to find the direction of triangles.
Here is my code in python to differentiate between the triangle/square and circle:
#blue_masking
mask_blue=np.copy(img1)
row,columns=mask_blue.shape
for i in range(0,row):
for j in range(0,columns):
if (mask_blue[i][j]==25):
mask_blue[i][j]=255
else:
mask_blue[i][j]=0
blue_edges = cv2.Canny(mask_blue,10,10)
kernel_blue = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2,2))
dilated_blue = cv2.dilate(blue_edges, kernel)
blue_contours,hierarchy =
cv2.findContours(dilated_blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in blue_contours:
area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt,True)
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
if(12<(perimeter*perimeter)/area<14.8):
shape="circle"
elif(14.8<(perimeter*perimeter)/area<18):
shape="squarer"
elif(18<(perimeter*perimeter)/area and area>200):
shape="triangle"
print(shape)
print(area)
print((perimeter*perimeter)/area,"\n")
cv2.imshow('mask_blue',dilated_blue)
cv2.waitKey(0)
cv2.destroyAllWindows()
Source image can be found here: img1
Please help, how can I found the direction of triangles?
Thank you.
Assuming that you only have four cases: [up, down, left, right], this code should work well for you.
The idea is simple:
Get the bounding rectangle for your contour. Use: box = cv2.boundingRect(contour_pnts)
Crop the image using the bounding rectangle.
Reduce the image vertically and horizontally using the Sum option. Now you have the sum of pixels along each axis. The axis with the largest sum determines whether the triangle base is vertical or horizontal.
To identify whether the triangle is pointing left/right or up/down: you need to check whether the bounding rectangle center is before or after the max col/row:
The code (assumes you start from the cropped image):
ver_reduce = cv2.reduce(img, 0, cv2.REDUCE_SUM, None, cv2.CV_32F)
hor_reduce = cv2.reduce(img, 1, cv2.REDUCE_SUM, None, cv2.CV_32F)
#For smoothing the reduced vector, could be removed
ver_reduce = cv2.GaussianBlur(ver_reduce, (3, 1), 0)
hor_reduce = cv2.GaussianBlur(hor_reduce, (1, 3), 0)
_,ver_max, _, ver_col = cv2.minMaxLoc(ver_reduce)
_,hor_max, _, hor_row = cv2.minMaxLoc(hor_reduce)
ver_col = ver_col[0]
hor_row = hor_row[1]
contour_pnts = cv2.findNonZero(img) #in my code I do not have the original contour points
rect_center, size, angle = cv2.minAreaRect(contour_pnts )
print(rect_center)
if ver_max > hor_max:
if rect_center[0] > ver_col:
print ('right')
else:
print ('left')
else:
if rect_center[1] > hor_row:
print ('down')
else:
print ('up')
Photos:
Well, Mark has mentioned a solution that may not be as efficient but perhaps more accurate. I think this one should be equally efficient but perhaps less accurate. But since you already have a code that finds triangles, try adding the following code after you have found triangle contour:
hull = cv2.convexHull(cnt) # convex hull of contour
hull = cv2.approxPolyDP(hull,0.1*cv2.arcLength(hull,True),True)
# You can double check if the contour is a triangle here
# by something like len(hull) == 3
You should get 3 hull points for a triangle, these should be the 3 vertices of your triangles. Given your triangles always 'face' only in 4 directions; Y coordinate of the hull will have close value to the Y coordinate of the centroid for triangle facing left or right and whether it's pointing left or right will depend on whether hull X is less than or greater than centroid X. Similarly use hull and centroid X and Y for triangle pointing up or down.
The text positioning (y) is determined by the TextPlusYExtractionStrategy perfectly when the rotation angle is 0 (portrait). In case of rotation angle is 90 degree (landscape) the position y provided from left to right instead of top to bottom. How to consider the rotation to get the text position y in when the page is 90 degree.
The below code helped me to resolve my issue.
if(rotation == 90){
chunkY = chunk.getLocation().getStartLocation().get(Vector.I1);
}
Constructor of TextPlusYExtractionStrategy can take the rotation angle, and use the Vector.I1 which is x co-ordinate of the chunk.
The issue will solve only the landscape (rotation=90) issue to find the Y coordinate of the search text.
Here some examples of twisted triangle prisms.
I want to know if a moving triangle will hit a certain point. That's why I need to solve this problem.
The idea is that a triangle with random coordinates becomes the other random triangle whose vertices all move between then
related: How to determine point/time of intersection for ray hitting a moving triangle?
One of my students made this little animation in Mathematica.
It shows the twisting of a prism to the Schönhardt polyhedron.
See the Wikipedia page for its significance.
It would be easy to determine if a particular point is inside the polyhedron.
But whether it is inside a particular smooth twisting, as in your image, depends on the details (the rate) of the twisting.
Let's bottom triangle lies in plane z=0, it has rotation angle 0, top triangle has rotation angle Fi. Height of twisted prism is Hgt.
Rotation angle linearly depends on height, so layer at height h has rotation angle
a(h) = Fi * h / Hgt
If point coordinates are (x,y,z), then shift point to z=0 and rotate (x,y) coordinates about rotation axis (rx, ry) by -a(z) angle
t = -a(z) = - Fi * z / Hgt
xn = rx + (x-rx) * Cos(t) - (y-ry) * Sin(t)
yn = ry + (x-rx) * Sin(t) - (y-ry) * Cos(t)
Then check whether (xn, yn) lies inside bottom triangle
My trigonometry needs a little help.
How would I go about calculating the point of the nearest possible intersection with a line along a rounded corner?
Take this image:
What I would like to know is, given that I know point a, and the dimensions of the rectangle, how would I find point b when the edges of the rectangle are curved?
So far, as you can see, I've only managed to calculate the nearest edge of the rectangle as if it had right-angled corners.
If it matters, I'm doing this in ActionScript 3. But example sudo-code will suffice.
Calculate the vector from the midpoint M of the corner to A:
v_x = a_x - m_x
v_y = a_y - m_y
then go radius of the corner r times towards A to get to the intersection point I
i_x = m_x + r*v_x
i_y = m_y + r*v_y
This obviously only works if the nearest intersection is on the rounded corner. Just calculate the other intersections with the edges, too, and then check which has the nearest distance to A.
You need to know the radius R of the circle that generates the round corner and the coordinates (Xr,Yr) of the point where the two sides of a non rounded rectangle cross each other.
Then the coordinates for the center of the circle that generates the round corner are (Xc, Yc) = (Xr-R, Yr-R)
From here, it's a matter of solving the equation of the cross point between the segment line defined by point A=(Xa, Ya) and point (Xc, Yc), whose parametric equation is:
x = Xa + p*(Xc-Xa)
y = Ya + p*(Yc-Ya)
and the circle whose equation is
(x-Xc)^2 + (y-Yc)^2 = R^2
Substitute values for x and y from the parametric euation of the line in the equation of the circle, and you will have an equation with only one unkown: p. Solve the equation, and if there are more than one solution, choose the one that is in the range [0,1]. Substitute the found value of p in the parametric equation of the line to get the point of intersection.
Graphically:
If you know the radius and center of the corner as R and C=(Xc, Yc), then the nearest point on the corner to the given point A=(Xa, Ya) is the intersection point of the corner and the line defined by the given point and the center. This point can be directly expressed as
X = Xc + R*(Xa-Xc)/|AC|
Y = Yc + R*(Ya-Yc)/|AC|
where |AC| = Sqrt((Xa-Xc)^2 + (Ya-Yc)^2)
EDIT - Thanks for all the answers everyone. I think I accidentally led you slightly wrong as the square in the picture below should be a rectangle (I see most of you are referencing squares which seems like it would make my life a lot easier). Also, the x/y lines could go in any direction, so the red dot won't always be at the top y boundary. I was originally going for a y = mx + b solution, but then I got stuck trying to figure out how I know whether to plug in the x or the y (one of them has to be known, obviously).
I have a very simple question (I think) that I'm currently struggling with for some reason. I'm trying to have a type of minimap in my game which shows symbols around the perimeter of the view, pointing towards objectives off-screen.
Anyway, I'm trying to find the value of the red point (while the black borders and everything in green is known):
It seems like simple trigonometry, but for some reason I can't wrap my head around it. I just need to find the "new" x value from the green point to the red point, then I can utilize basic math to get the red point, but how I go about finding that new x is puzzling me.
Thanks in advance!
scale = max(abs(x), abs(y))
x = x / scale
y = y / scale
This is the simple case, for a square from (-1, -1) to (1, 1). If you want a different sized square, multiply the coordinates by sidelen / 2.
If you want a rectangle instead of a square, use the following formula. (This is another solution to the arbitrarily-sized square version)
scale = max(abs(x) / (width / 2), abs(y) / (height / 2))
x = x / scale
y = y / scale
Let's call the length of one side of the square l. The slope of the line is -y/x. That means, if you move along the line and rise a distance y toward the top of the square, then you'll move a distance x to the left. But since the green point is at the center of the square, you can rise only l/2. You can express this as a ratio:
-y -l/2
——— = ———
x d
Where d is the distance you'll move to the left. Solving for d, we have
d = xl/2y
So if the green dot is at (0, 0), the red dot is at (-l/2, xl/2y).
All you need is the angle and the width of the square w.
If the green dot is at (0,0), then the angle is a = atan(y/x), the y-coordinate of the dot is w/2, and therefore the x-coordinate of the dot is tan(1/a) * (w/2). Note that tan(1/a) == pi/2 - tan(a), or in other words the angle you really want to plug into tan is the one outside the box.
Edit: yes, this can be done without trig, too. All you need is to interpolate the x-coordinate of the dot on the line. So you know the y-coordinate is w/2, then the x-coordinate is (w/2) * x/y. But, be careful which quadrant of the square you're working with. That formula is only valid for -y<x<y, otherwise you want to reverse x and y.