Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to find the euclidean distance in 3d using mysql?

I have a MySQL table with thousands of data points stored in 3 columns R, G, B. how can I find which data point is closest to a given point (a,b,c) using Euclidean distance?

I'm saving RGB values of colors separately in a table, so the values are limited to 0-255 in each column. What I'm trying to do is find the closest color match by finding the color with the smallest euclidean distance.

I could obviously run through every point in the table to calculate the distance but that wouldn't be efficient enough to scale. Any ideas?

like image 673
soulkphp Avatar asked Jun 08 '12 04:06

soulkphp


People also ask

How do you calculate Euclidean distance in SQL?

Euclidean Distance = SquareRoot(((x2-x1)^2)+((y2-y1)^2)) SquareRoot can be written as (something)^(0.5) I implemented like that. CAST(ROUND(LONG_W ,4) as numeric(36,4)) is for taking value upto 4 decimal point.

How does MySQL calculate distance?

Heres is MySQL query and function which use to get distance between two latitude and longitude and distance will return in KM. SELECT getDistance($lat1,$lng1,$lat2,$lng2) as distance FROM your_table. Almost a decade later, this function gives THE SAME results as Google Maps distance measurement.

How can I find the distance between two points in MySQL?

Calculating Distance in MySQL To get the distance between two points, you call the function with the two points as the arguments: -- Returns distance in meters.

Which one is the correct Euclidean distance formula from given options?

The Euclidean distance formula is used to find the distance between two points on a plane. This formula says the distance between two points (x1 1 , y1 1 ) and (x2 2 , y2 2 ) is d = √[(x2 – x1)2 + (y2 – y1)2].


1 Answers

I think the above comments are all true, but they are - in my humble opinion - not answering the original question. (Correct me if I'm wrong). So, let me here add my 50 cents:

You are asking for a select statement, which, given your table is called 'colors', and given your columns are called r, g and b, they are integers ranged 0..255, and you are looking for the value, in your table, closest to a given value, lets say: rr, gg, bb, then I would dare trying the following:

select min(sqrt((rr-r)*(rr-r)+(gg-g)*(gg-g)+(bb-b)*(bb-b))) from colors;

Now, this answer is given with a lot of caveats, as I am not sure I got your question right, so pls confirm if it's right, or correct me so that I can be of assistance.

like image 107
David Svarrer Avatar answered Sep 24 '22 09:09

David Svarrer