I'm trying to find a way to look for colors in images. Here's a simplified example:
tree = ExampleData[{"TestImage", "Tree"}]
I can see there's blue in there, so I want an xy location somewhere in that sea of pixels. Say I'm looking for a particular shade of blue, which I can supply some approximate RGB values for:
Manipulate[Graphics[{RGBColor[r, g, b], Disk[]}], {r, 0, 1}, {g, 0, 1}, {b, 0, 1}]
and now I want to find the coordinates of some pixels which have that value, or near enough. Nearest
might be able to do it:
Nearest[ImageData[tree], {0.32, 0.65, .8}]
but doesn't - it 'generates a very large output'...
It's the reverse of doing this:
ImageValue[tree, {90, 90}]
which is OK if I've got the numbers already, or can click on the image. Once the location of the colors I want is known, I can then supply this to functions that require 'markers' - such as RegionBinarize
.
I feel there must be a Mathematica function for this, but can't find it yet...
To detect colors in images, the first thing you need to do is define the upper and lower limits for your pixel values. Once you have defined your upper and lower limits, you then make a call to the cv2. inRange method which returns a mask, specifying which pixels fall into your specified upper and lower range.
We use Counter to get count of all labels. To find the colors, we use clf.
Color schemes detection Computer Vision analyzes the colors in an image to provide three different attributes: the dominant foreground color, the dominant background color, and the larger set of dominant colors in the image.
Does this
Position[#, First@Nearest[Flatten[#, 1], {0.32, 0.65, .8}]] &@
ImageData[tree]
(*
{{162, 74}}
*)
do what you want?
OK, try this:
tree = ExampleData[{"TestImage", "Tree"}];
dat = Reverse[ImageData[tree]\[Transpose], {2}];
dim = Dimensions[dat][[{1, 2}]];
nearfunc = Nearest[Join @@ dat -> Tuples @ Range @ dim];
Manipulate[
rgb = Extract[dat, Ceiling[p]];
posns = nearfunc[rgb, num];
Graphics[{
Raster[dat\[Transpose]], Red, Point[posns]
}],
{{p, {10, 10}}, Locator},
{{num, 20}, 1, 100, 1}
]
this lets you click somewhere on the image, determines a number of points that are closest (according to the default norm) to the colour of that point, and displays them. num
is the number of points to be shown.
It looks like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With