Repository navigation
Description
Is your feature request related to a problem? Please describe.
In my project I want to detect 2x8+ color plates on train tracks on a train with a Color & Distance sensor pointed down at the tracks. The reliability of detecting them correctly is very important. In the past, I've tried to use ColorDistanceSensor.color() along with custom detectable colors for this, but I found that using my own detection algorithm using the following error function worked much more reliably (edit: see below comment for correction):
sdelta = (color.s-test_color.s)
hdelta = ((color.h-test_color.h + 180) % 360) - 180
vdelta = color.v-test_color.v
err = 2*sdelta*sdelta + hdelta*hdelta + vdelta*vdeltaNotice that I doubled the weight for the saturation delta compared to the hue and value.
Describe the solution you'd like
The above solution probably slower and more memory-intensive than just using the builtin color matching, so I propose that we could introduce a custom weighting for hue, saturation and value in ColorDistanceSensor.color() to make it more flexible for such usecases. We could also choose between squared sum of the errors or just the sum of absolutes (or more?).
My proposed API for this would change the parameters of ColorDistanceSensor.detectable_colors(colors) to:
ColorDistanceSensor.detectable_colors(colors, hsv_weights, method)
where hsv_weights might be a tuple of weights and method could be either "squared", "linear" (or an arbitrary integer exponent > 0).
Another method could be to perform the delta in RGB space (though I realize converting to rgb is not trivial depending on the resources we want to spend on this).
Another possibility could be to provide a custom micropython callable for the error function, but then the advantage over matching the color fully in micropython might diminish.
Describe alternatives you've considered
One could implement the matching in micropython as above, which costs performance and memory.
Additional context
This issue is inspired by the discussion in #619 (comment)
Activity
laurensvalk commentedon Feb 4, 2022
Actually, not really: Fun fact, it sounds like we are almost doing exactly the same. Our current cost function is:
So maybe these weights should be configurable. It would be great if you want to have a look through the referenced code to see if you can find any mistakes.
I'm also open to changing the default weights if we find that yours are better across a range of applications.
The original data is RGB so this is possible. In general we seem to be getting better results with HSV though.
Novakasa commentedon Feb 4, 2022
I was aware that the cost function looks similar, but I assume that implementing it in C is more efficient than running it in micropython.
I had referenced the source code as well when working on this, but was surprised just now to see that it seems to use a large weight for saturation. After looking into it, I might have referenced the wrong version of my implementation, since in a previous version I had used this:
Which is equivalent to the weight 8 in saturation, 4 in hue and 1 in value. This approach should have been the one that was more reliable for me than default color matching.
Since I am now using a quite different approach, as outlined in #619 (comment) I don't use an error function like this for development anymore, but since I have dumped my logged data to PC, it might be easy for me to try to get reliable weights for the error function.
Novakasa commentedon Feb 4, 2022
Probably the main reason for bad performance of the original function is the noise in the hue due to the low saturation of the dark gray tracks and the black floor.
Here is the data for a train driving over [blue, green, red, blue] markers in HSV and RGB:


So maybe the proper way to match colors would be to calculate the euclidean distance in the hsv cone:

One can still use different weights for the "dimensions" of the cone.
At some point I did try this by basically copying from here: https://stackoverflow.com/a/39113477
But it did not immediately work and I did not spend much time trying to debug it.
dlech commentedon Feb 4, 2022
Is "black" or "no color" in your list of matching colors? I tried a similar train color sensor project a few months ago (I didn't use it extensively, so I don't know how reliable it was long term). I found that if I only put the colors I wanted to match in the list (using the built-in color matching) then there were errors. But if I also included "colors" I didn't want, which included the color of the track and the color of the floor underneath the track, then the matching seemed to work fairly well.
dlech commentedon Feb 4, 2022
Can you add a scale to the graphs so that we can see what the threshold is for the noise levels?
Novakasa commentedon Feb 4, 2022
Yes, that was one of the first realizations for me as well. For detectable colors I included the track sleepers, the floor, and each of the markers colors
Sorry about that. There are actually scales, but due to transparency they don't show up well in dark mode on github. If I click on the images, I can see the scales though.
dlech commentedon Feb 4, 2022
Sure enough - if you squint you can see them.
Novakasa commentedon Feb 4, 2022
Here is the data for the above plots, and the plots without transparency.
Note that in this snippet I multiply the hue data by 2 since I halfed it on the hub for sending it in a bytearray. Also, the data should be "rolled" by the
dump_indexsince that's the index where it last updated the data.Novakasa commentedon Feb 4, 2022
For completeness, that's the code for getting to the hsv plot:
Novakasa commentedon Feb 4, 2022
Here is the graph for a slower train. The earlier part has less noise, probably because that area has a white background (I put white paper sheets under the track). At the end, the black background produces the hue noise probably.

The data:
dlech commentedon Feb 4, 2022
After just a quick glance at the code, it looks like we might need to increase our thresholds for low value and low saturation quite a bit. We may also need to make these dependent on the sensor type.
I also wonder if it would be possible to do some sort of discrete time analysis of the hue and saturation to detect if these signal are currently "noisy" or not instead of the current method of "if X is below threshold then Y is noisy".
laurensvalk commentedon Feb 4, 2022
Did you use the standard colors like
Color.REDor did you provide your own?laurensvalk commentedon Feb 4, 2022
This is probably where the documentation should be clearer. The intention is indeed to include all colors that it can detect in your application.
Maybe
distinguishableis a better word thandetectable(but it is harder to spell 😄)6 remaining items
Novakasa commentedon Feb 6, 2022
One can choose a different weight for the z-scale of the cone (=value), increasing this gives increased sensitivity between the dark colors in the cartesian error estimate:

Novakasa commentedon Feb 6, 2022
I have now managed to set the environment up (using windows subsystem for linux) and can compile the firmware, so I will work on a pull request for this. Since the mapping requires trigonometric functions, is there a implementation for fixed point sine/cosine in the codebase that I can use? I am guessing that we want to avoid floating point functions because Move Hub doesn't have floats.
dlech commentedon Feb 6, 2022
We are using https://github.com/PetteriAimonen/libfixmath already.
lib/libfixmath/in thepybricks-micropythonrepository.util_pb/pb_color_map: HSV cone distance as error
util_pb/pb_color_map: HSV cone distance as error
util_pb/pb_color_map: HSV cone distance as error
util_pb/pb_color_map: HSV cone distance as error
util_pb/pb_color_map: HSV cone distance as error
dlech commentedon Mar 1, 2025
The pull request got merged quite a while ago, so I think we can close this one.