Distance between two points in OpenCv based on known measurement [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I have an image in which, I have two set of coordinates between which I have draw a line.
#Get image
im_res = requests.get(image_url)
img = Image.open(BytesIO(im_res.content))
img = np.asarray(img)
#Draw first line
lineThickness = 3
cv.line(img, (ax, ay), (bx, by), (0,255,0), lineThickness)
#Draw second line
lineThickness = 3
cv.line(img, (cx, cy), (dx, dy), (0,255,0), lineThickness)
cv.imshow("Image", img)
cv.waitKey(0)
cv.destroyAllWindows()
Coordinates are A,B,C & D. I know the distance between C to D. However, the distance between A to B is unknown. What is the best way to calculate this in OpenCv?
Is there an OpenCv specific function or method to do this? Especially the distance we are taking about is in pixels? I am sorry if this question is foolish, I really don't want to to end up getting wrong values due to lack of understanding in this topic.
I saw certain references to cv2.norm() and cv2.magnitude() as solution to this problem. However, I quite didnt't understand how to choose for my situation, keeping in mind in this case the distance is within an image/photo.

Compute Euclidean from C to D and find the ratio of that with the known measurement.
ratio = known / Euclidean
Then find the Euclidean between A & B and use the earlier found ratio to convert the Euclidean to actual distance.
distance = euclidean * ratio
euclidean "sqrt((x2-x1)**2+(y2-y1)**2)"

Related

Find the coordinates of the point at the tail of the fish [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I tried it a number of times and consulted some solutions but it really didn't work out as expected. Hope people can give me the solution and some example.
I've attached a picture if you want to use it to run code for your program.
I want to find the coordinates of the point like the picture
I'm not sure what you exactly want; whether all points within the gap or the one in the innermost curve of the gap, or something else.
Regardless, I hope you find this a little helpful even if you are not trying to do the second.
Since I don't have your original image and assuming that the image you are working with doesn't contain the red circle, I downloaded your image and erased part of the red circle into something like this: https://i.stack.imgur.com/ySuY7.jpg (apologies for I do not have enough rep to embed images)
import cv2
import numpy as np
img = cv2.imread("Inkedfish.jpg")
# some preprocessing
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = cv2.dilate(img2, (3,3))
img2 = cv2.blur(img2, (3, 3))
_, thresh = cv2.threshold(img2, 10, 255, 0)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0]
hull = cv2.convexHull(contours, returnPoints=False)
defects = cv2.convexityDefects(contours, hull)
# there are 3 most plausible points at the tail:
# the edges of the tail, and the innermost curve.
# Based on the image we can infer that the
# point on the innermost curve should come before
# the other two thus we do [-3]
contour_idxs = np.sort(defects[:,:,2], axis=1)
point = contours[contour_idxs[-3, 0], 0]
cv2.circle(img, point, 5, (0,0,255), -1)
result: https://i.stack.imgur.com/nE7BJ.png
EDIT:
Changing cv2.dilate to img2 = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, (3, 3)) seem to work as intended.

opencv align two images by keypoints [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have two images
image1(dog): Download link
image2 (bird):
I want to align image2 on image1 by keypoints. So the goal that both keypoints overlaps and the bird image is resized and scaled on top of the dog image.
Image 1 with keypoints:
Image two with keypoints:
This are my keypoints (csv file). The coordinates are x and y in the original image (download links at top):
bird_x,bird_y,dog_x,dog_y
0,43,265,48
88,12,297,29
172,1,332,23
211,17,349,32
283,60,378,60
143,109,321,98
How can I do this with opencv and python?
A quick rough way to do it is by resizing the smaller image to the bounding box formed by the keypoints of the bigger image.
import cv2
import numpy as np
img_dog = cv2.imread("akita.jpg")
img_bird = cv2.imread("gull.png")
#Reconstruct the keypoints
bird_keypoints = ((0,43), (88,12), (172,1), (211,17), (283,60), (143,109))
dog_keypoints = ((265,48), (297,29), (332,23), (349,32), (378,60), (321, 98))
#New dimension of the smaller image - calculate keypoints max x and y range
min_x = min([p[0] for p in dog_keypoints])
max_x = max([p[0] for p in dog_keypoints])
min_y = min([p[1] for p in dog_keypoints])
max_y = max([p[1] for p in dog_keypoints])
scale_height = max_y - min_y
scale_width = max_x - min_x
center = (0.5*(min_x + max_x), 0.5*(min_y + max_y))
#resize smaller image
img_bird_scaled = cv2.resize(img_bird, (scale_width,scale_height),
interpolation=cv2.INTER_AREA)
#overwrite part of the dog image with the new scaled smaller image
img_dog[min_y:max_y, min_x:max_x] = img_bird_scaled
cv2.imshow("test", img_dog)
If you need to paste only the bird without the background, you will have to deal with the alpha channel.

How to find angle between two ellipses in an Image? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
An image has two ellipses ( for simple case we can consider both ellipses are same). One of ellipse is rotated and translated from the other. We have only image of these ellipses. How to estimate rotation angle ( angle between two ellipses) ?
I will present some initial pre-processing steps and then with the use of some OpenCV internal methods, we can get what you are asking for.
If the image is RGB or RGBA:
convert it to GRAY [use cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)]
Threshold the image to get a binary image with 2 ellipses. [cv2.threshold()]
Find contours in the binary image [cv2.findContours()]
Call the cv2.fitline() on each contour to get the line equation.
Apply the formula to get the angle between 2 lines.
For more operations on contours visit http://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html
Off the top of my head, I'd do this: (considering the tags, I assume you're using opencv)
1-Use "findContours" command to get the boundaries' pixels of each ellipsis separately.
2-For each ellipsis, calculate the distance between each pairs of pixels (for all pixels in the boundary - in a dual loop) by the equation:(D=sqrt((y1-y2)^2 + (x1-x2)^2)) and find the pair that shows the most distance. This pair comprises of two ends of the major axis of the ellipsis.
3-Using two mentioned points, calculate the angle of the major axis with respect to x-axis of the image by the equation:
angle = arctan((y2-y1)/(x2-x1))
4-Find the angle for the other ellipsis and subtract two angles to find the angle between them.

How to detect the nearest square to the image center points? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How do I discover the nearest square to the center of the image?
I already have the square's vertices and the center, just need to find out which square is closest to the center.
I have a problem similar to this image. I would like to select the nearest square (the red square).
Two possibilities, of which one is mentioned in your answer and the comment by #miki
Square center
You do not need to implement your own distance function. SciPy already has a few. For example your euclidean distance in scipy.spatial.distance.euclidean:
from scipy.spatial import distance
distance.euclidean((x0, y0), (x1, y1))
No need to reinvent the wheel.
Square edges
In the following example it can be argued whether the red or the blue square are closer to the center. By euclidean distance, it is the blue one. The red one is overlapping the center, though.
If you wanted to have the square with the closest pixel to the center, you could do something like
square = (upper_left_x, upper_left_y, lower_right_x, lower_right_y)
center = (x, y)
if upper_left_x <= x <= lower_right_x and upper_left_y <= y <= lower_right_y:
return 0 # point in square
elif upper_left_x <= x <= lower_right_x: # on vertical line
return min(upper_left_y -y, lower_right_y - y)
elif upper_left_y <= y <= lower_right_y: # on horizontal line
return min(upper_left_x -x, lower_right_x - x)
else:
points = []
for x in (upper_left_x, lower_right_x):
for y in (upper_left_y, lower_right_y):
points.append((x,y))
return min([distance.euclidean((x,y), p) for p in points])
Original answer before edit to question
You can split this up:
import image
find the squares
find the corners
connect them
compute distance to image center
The main point here may be any of them (except for 1.2 probably).
There is a neat OpenCV Python tutorial, which tells you how to do some of that. Let us start:
import
import cv2
img = cv2.imread('L3h9H.png')
imports the image.
To see that you imported correctly, you can use
from matplotlib import pyplot as plt
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
which shows it to you.
find corners
import numpy as np
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray, 2,3,0.04)
for i, valx in enumerate(dst):
for j, valy in enumerate(valx):
if valy > 0:
print '%s, %s: %s' % (i, j, valy)
Finds corner using one of the built-in algorithms. The corners are listed afterwards.
Next steps would be:
compute lines between corners (maybe).
Show min distance of line to image center.
Say if you need more help.
This is the solution I have for my problem. Where the x0 and y0 can be the coordinates of the center of my image and the x1 and y1 will be center of coordinates of the square center.
import math
def dist(x0, y0, x1, y1):
a = (x1 - x0)**2 + (y1 - y0)**2
b = math.sqrt(a)
return b
print dist(5, 5, 4, 6)
print dist(5, 5, 9, 2)

Extract RGB using simpleCV [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'll use this picture as an example
I need to extract the RGB values and compare them with all of the color values to see if I can figure out which color is in it without hard coding it.
For example I get (4,5,0) and I determined this color = red. I don't know if those are the real values of red, but it's an example.
How can I extract the RGB values from the inside of the red box and how can I search for the color that corresponds to those values.
this is what I tried:
img = Image('car.png')
pixel = img.getPixel(120, 150)
print(pixel)
This retrieves the rgb on those dimensions, but I need an average around that whole box.
Please explain solution, thanks
Here's an idea of what you should do:
width = XX
height = YY
#crops to (x1,y1) to (x2,y2) when x2>x1 and y2>y1
frame = img[width/4:(width/4+width/2), height/4:(height/4+height/2)]
And then,
r = np.array(frame[:,:,0])
avg_r = np.average(r)
Repeat for G and B.

Categories

Resources