How to find distance between two connected points through white pixels? - matlab

I want to find the two endpoints of a curve.
I used convex hull to find 8 boundary-points and then for every point, distances with all other points are calculated. The points with maximum distances are assumed to be the endpoints. It works for most of the cases when the shape is simple, like below:
I'm using this code to find the two points:
% Calculate 8-boundary points using Convex Hull
% (points consists of all white pixels for the curve)
out=convhull(points);
extremes=points(out,:);
% Finding two farthest points among above boundary points
arr_size = size(extremes);
max_distance = 0;
endpoints = [extremes(1,:); extremes(2,:)];
for i=1:arr_size(1)
p1 = extremes(i,:);
for j=i+1:arr_size(1)
p2 = extremes(j,:);
dist = sqrt((p2(1)-p1(1))^2 + (p2(2)-p1(2))^2);
if dist>max_distance
max_distance = dist;
endpoints = [p1; p2];
end
end
end
disp(endpoints);
In most of the cases it works, but the issue comes when it is applied on U-typed shape.
I want to find out the number of white pixels between the two points. I followed this
Counting white pixels between 2 points in an image but it helps in case of only straight lines not for curve. Any help appreciated!
EDIT 1 :
I have updated my code based on the answer by #Rotem and it fixed my problem.
Updated Code:
for i=1:arr_size(1)
p1 = extremes(i,:);
distanceMap = calculate_distance_map(arr, p1);
for j=i+1:arr_size(1)
p2 = extremes(j,:);
dist = distanceMap(p2(2), p2(1));
if dist>max_distance
max_distance = dist;
endpoints = [p1; p2];
end
end
end
However it takes significantly much time. Any suggestions on how to reduce the calculation time?

I found a solution inspired by dynamic programming algorithms.
Explanations are in the comments:
function n_points = BlueDotsDist()
I = imread('BlueDots.png');
%Fix the image uploaded to the site - each dot will be a pixel.
I = imresize(imclose(I, ones(3)), 1/6, 'nearest');
%Convert each color channel to a bynary image:
R = imbinarize(I(:,:,1));G = imbinarize(I(:,:,2));B = imbinarize(I(:,:,3));
%figure;imshow(cat(3, double(R), double(G), double(B)));impixelinfo
%Find blue dost:
[blue_y, blue_x] = find((B == 1) & (R == 0));
%Compute distance map from first blue point
P = CalcDistMap(R, blue_y(1), blue_x(1));
%Compute distance map from second blue point
Q = CalcDistMap(R, blue_y(2), blue_x(2));
%Get 3x3 pixels around second blue point.
A = P(blue_y(2)-1:blue_y(2)+1, blue_x(2)-1:blue_x(2)+1);
dist_p = min(A(:)); %Minimum value is the shortest distance from first point (but not the number of white points).
T = max(P, Q); %Each element of T is maximum distance from both points.
T(T > dist_p) = 10000; %Remove points that are more far than dist_p.
%Return number of white points between blue points.
n_points = sum(T(:) < 10000);
function P = CalcDistMap(R, blue_y, blue_x)
%Each white pixel in R gets the distance from the blue dot in coordinate (blue_x, blue_y).
%Initialize array with values of 10000 (high value - marks infinite distance).
P = zeros(size(R)) + 10000; %P - distance from blue dot
P(blue_y, blue_x) = 0; %Distance from itself.
prvPsum = 0;
while (sum(P(:) < 10000) ~= prvPsum)
prvPsum = sum(P(:) < 10000); %Sum of "marked" dots.
for y = 2:size(R, 1)-1
for x = 2:size(R, 2)-1
p = P(y, x);
if (p < 10000) %If P(y,x) is "marked"
A = P(y-1:y+1, x-1:x+1); %3x3 neighbors.
A = min(A, p+1); %Distance is the minimum of current distance, and distance from p pixel + 1.
A(R(y-1:y+1, x-1:x+1) == 0) = 10000; %Ignore black pixels.
A(P(y-1:y+1, x-1:x+1) == 0) = 0; %Restore 0 in blue point.
P(y-1:y+1, x-1:x+1) = A; %Update distance map.
end
end
end
end
Illustration of distance maps (10000 replaced with zero):
P (distances from first blue point):
Q (distances from second blue point):
max(P, Q):
T:

Related

Separate Double Moon Classification with A Line in Matlab

I have some Matlab code lines for drawing Double Moon Classification:
function data=dm(r,w,ts,d)
clear all; close all;
if nargin<4, w=6;end
if nargin<3, r=10;end
if nargin<2, d=-4;end
if nargin < 1, ts=1000; end
ts1=10*ts;
done=0; tmp1=[];
while ~done,
tmp=[2*(r+w/2)*(rand(ts1,1)-0.5) (r+w/2)*rand(ts1,1)];
tmp(:,3)=sqrt(tmp(:,1).*tmp(:,1)+tmp(:,2).*tmp(:,2));
idx=find([tmp(:,3)>r-w/2] & [tmp(:,3)<r+w/2]);
tmp1=[tmp1;tmp(idx,1:2)];
if length(idx)>= ts,
done=1;
end
end
data=[tmp1(1:ts,:) zeros(ts,1);
[tmp1(1:ts,1)+r -tmp1(1:ts,2)-d ones(ts,1)]];
plot(data(1:ts,1),data(1:ts,2),'.r',data(ts+1:end,1),data(ts+1:end,2),'.b');
title(['Perceptron with the double-moon set at distance d = ' num2str(d)]),
axis([-r-w/2 2*r+w/2 -r-w/2-d r+w/2])
save dm r w ts d data;
Results:
My question is how to put a line into the Double Moon Classification so that can separate both classification in Matlab code?
I have made a simulation of your problem and wrote a pragmatic solution based on the steps
generates a grid of points fine enough(step size as small as
possible)
find which of these points are in the space between both points
groups
find which points have an equal distance to both groups
plot points
The main part (without my data generation code and the plot I did) of the code is
PBlues = data(1:ts,:);
PReds = data(ts+1:end,:);
Xs = linspace( min(data(:,1)), max(data(:,1)), 100);
Ys = linspace( min(data(:,2)), max(data(:,2)), 100);
[Xs,Ys] = meshgrid( Xs, Ys);
%% compute point relative distance to each point set (ble and red)
bCouldbeInbetween = false(size(Xs));
minDistsb = zeros(size(Xs));
minDistsr = zeros(size(Xs));
for p=1:numel(Xs)
distb = sqrt( (Xs(p)- PBlues(:,1)).^2+(Ys(p)- PBlues(:,2)).^2);
distr = sqrt( (Xs(p)- PReds(:,1)).^2+(Ys(p)- PReds(:,2)).^2);
minDistsb(p) = min(distb);
minDistsr(p) = min(distr);
i = find(distb == minDistsb(p));
j = find(distr == minDistsr(p));
bCouldbeInbetween(p) = (sign(PBlues(i,1)-Xs(p)) ~= sign(PReds(j,1)-Xs(p))) || ...
(sign(PBlues(i,2)-Ys(p)) ~= sign(PReds(j,2)-Ys(p)));
if bCouldbeInbetween(p)
end
end
% point distance difference to each point set
DistDiffs = abs(minDistsb - minDistsr);
% point with equal distance using proportional decision strategy
bCandidates = DistDiffs./ max(minDistsb,minDistsr) < 0.05;
medianLine = [Xs(bCandidates),Ys(bCandidates)];
[~,I] = sort(medianLine(:,1));
medianLine(:,1) = medianLine(I,1);
medianLine(:,2) = medianLine(I,2);
I hope this helps
I have just made a submission which can be downloaded here: https://de.mathworks.com/matlabcentral/fileexchange/66618-linebetweentwopointsgroups-exchange--

Summarize all intersection points by clockwise direction

This a program that I have, I already asked before for how to find the intersection on my image with a circle, and somebody has an answer it (thank you) and I have another problem...
a = imread('001_4.bmp');
I2 = imcrop(a,[90 5 93 180]);
[i,j]=size(I2);
x_hist=sum(I2,1);
y_hist=(sum(I2,2))';
x=1:j ; y=1:i;
centx=sum(x.*x_hist)/sum(x_hist);
centy=sum(y.*y_hist)/sum(y_hist);
BW = edge(I2,'Canny',0.5);
bw2 = imcomplement(BW);
circle = int32([centx,centy,40]);%<<----------
shapeInserter = vision.ShapeInserter('Fill',false);
release(shapeInserter);
set(shapeInserter,'Shape','Circles');
% construct binary image of circle only
bwCircle = step(shapeInserter,true(size(bw2)),circle);
% find the indexes of the intersection between the binary image and the circle
[i, j] = find ((bw2 | bwCircle) == 0);
figure
imshow(bw2 & bwCircle) % plot the combination of both images
hold on
plot(j, i, 'r*') % plot the intersection points
K = step(shapeInserter,bw2,circle);
[n,m]=size(i);
d=0;
k=1;
while (k < n)
d = d + sqrt((i(k+1)-i(k)).^2 + (j(k+1)-j(k)).^2);
k = k+1;
end
Q: How can I calculate all the existing intersection values(red *) in a clockwise direction?
Not sure, but I think that your teacher meant something different from the answer given in the previous question, because
CW direction can be a hint, not a additional problem
I've seen no clue that the circle should be drawn; for small radius circles are blocky and simple bw_circle & bw_edges may not work. For details please see "Steve on image processing" blog, "Intersecting curves that don't intersect"[1]
May be your teacher is rather old and wants Pascal-stile answer.
If my assumptions are correct the code below should be right
img = zeros(7,7); %just sample image, edges == 1
img(:,4) = 1; img(sub2ind(size(img),1:7,1:7)) = 1;
ccx = 4; % Please notice: x is for columns, y is for rows
ccy = 3;
rad = 2;
theta = [(pi/2):-0.01:(-3*pi/2)];
% while plotting it will appear CCW, for visual CW and de-facto CCW use
% 0:0.01:2*pi
cx = rad * cos(theta) + ccx; % gives slightly different data as for
cy = rad * sin(theta) + ccy; % (x-xc)^2 + (y-yc)^2 == rad^2 [2]
ccoord=[cy;cx]'; % Once again: x is for columns, y is for rows
[ccoord, rem_idx, ~] =unique(round(ccoord),'rows');
cx = ccoord(:,2);
cy = ccoord(:,1);
circ = zeros(size(img)); circ(sub2ind(size(img),cy,cx))=1;
cross_sum = 0;
figure, imshow(img | circ,'initialmagnification',5000)
hold on,
h = [];
for un_ang = 1:length(cx),
tmp_val= img(cy(un_ang),cx(un_ang));
if tmp_val == 1 %the point belongs to edge of interest
cross_sum = cross_sum + tmp_val;
h = plot(cx(un_ang),cy(un_ang),'ro');
pause,
set(h,'marker','x')
end
end
hold off
[1] https://blogs.mathworks.com/steve/2016/04/12/intersecting-curves-that-dont-intersect/
[2] http://matlab.wikia.com/wiki/FAQ#How_do_I_create_a_circle.3F

Simulating random walkers which can not collide into each other in Matlab

I have written a code to simulate the motion of circular particles in a 2d box. Whenever they move out of the box, I put them inside the box and near the wall. I want to add the diameter (2R) of particles in the code, which means when the distance between the center of two circles become less than 2R, they separate along the line connecting their centers so that the distance between the centers of the circles becomes equal to 2R.
Could anyone suggest a code to perevent the overlapping of particles?
This is my code in which overlap is not considered:
clear all
close all
l = 224; nn = 800; %number of particles
time = 1000; dd = 1;
x= l*rand(1,nn);
y= l*rand(1,nn);
for t = 1:time;
x= x + rand(1,nn)-0.5* ones(1,nn);
y=y+rand(1,nn)-0.5* ones (1,nn);
index = (x < 0); x(index) = abs(normrnd(0,1,1,nnz(index)));
index = (y < 0); y(index) = abs(normrnd(0,1,1,nnz(index)));
index = (x > l); x(index) = l-abs(normrnd(0,1,1,nnz(index)));
index = (y > l); y(index) = l-abs(normrnd(0,1,1,nnz(index)));
end
Here is some commented code which does what you want. Notably:
psize is some defined particle size for interaction.
point-to-point distances found using pdist2.
points that are too close are moved away from each other by some amount (dp times their current distances, if dp=1/2 then their x and y distances double) until there are no clashes.
See comments for details.
clear; close all;
l = 224; nn = 800; % number of particles
time = 100;
x = l*rand(1,nn); y = l*rand(1,nn);
psize = 2; % Particle size for interaction
dp = 0.1;
figure; hold on; axis([0 l 0 l]);
for t = 1:time;
% Random movement
movement = 2*rand(2,nn)-1;
x = x + movement(1,:);
y = y + movement(2,:);
index = (x < 0); x(index) = abs(normrnd(0,1,1,nnz(index)));
index = (y < 0); y(index) = abs(normrnd(0,1,1,nnz(index)));
index = (x > l); x(index) = l-abs(normrnd(0,1,1,nnz(index)));
index = (y > l); y(index) = l-abs(normrnd(0,1,1,nnz(index)));
% Particle interaction. Loop until there are no clashes. For
% robustness, some max iteration counter should be added!
numclash = 1;
while numclash > 0
dists = pdist2([x;y]', [x;y]'); % Distances between all particles
dists(dists < psize) = NaN; % Those too close are assigned NaN
tooclose = isnan(tril(dists,-1)); % All NaNs identified by logical
[clash1,clash2] = find(tooclose); % Get particles which are clashing
numclash = numel(clash1); % Get number of clashes
% All points where there was a clash, move away from each other
x(clash1) = x(clash1) + (x(clash1)-x(clash2))*dp;
x(clash2) = x(clash2) - (x(clash1)-x(clash2))*dp;
y(clash1) = y(clash1) + (y(clash1)-y(clash2))*dp;
y(clash2) = y(clash2) - (y(clash1)-y(clash2))*dp;
end
% Plot to visualise results. Colour fade from dark to bright green over time
scatter(x,y,'.','markeredgecolor',[0.1,t/time,0.4]);
drawnow;
end
hold off
Result:
Edit:
For a clearer diagram, you could initialise some colour matrix C = rand(nn,3); and plot using
scatter(x,y,[],C*(t/time),'.'); % the (t/time) factor makes it fade from dark to light
This would give each particle a different colour, which also fade from dark to light, rather than just fading from dark to light as before. The result would be something like this:

How to square the corners of a "rectangle" in a bw image with matlab

I have images of rectangles or deformed rectangles with rounded corners, like this:
or this:
is there a way to make the corners squared with matlab?
And then how can i get the coordinates of those new corners?
Thank you
Explanation
This problem is similar to the following question. My answer will be somehow similar to my answer there, with the relevant modifications.
we want to find the parallelogram corners which fits the most to the given shape.
The solution can be found by optimization, as follows:
find an initial guess for the 4 corners of the shape. This can be done by finding the boundary points with the highest curvature, and use kmean clustering to cluster them into 4 groups.
create a parallelogram given these 4 corners, by drawing a line between each pair of corresponding corners.
find the corners which optimize the Jaccard coefficient of the boundary image and the generated parallelogram map.
The optimization will done locally on each corner, in order to spare time.
Results
Initial corner guess (corners are marked in blue)
final results:
Code
main script
%reads image and binarize it
I = rgb2gray(imread('eA4ci.jpg')) > 50;
%finds boundry of largerst connected component
boundries = bwboundaries(I,8);
numPixels = cellfun(#length,boundries);
[~,idx] = max(numPixels);
B = boundries{idx};
%finds best 4 corners
[ corners ] = optimizeCorners(B);
%generate line mask given these corners, fills the result
linesMask = drawLines(size(I),corners,corners([2:4,1],:));
rectMask = imfill(linesMask,'holes');
%remove biggest CC from image, adds linesMask instead
CC = bwconncomp(I,8);
numPixels = cellfun(#numel,CC.PixelIdxList);
[~,idx] = max(numPixels);
res = I;
res(CC.PixelIdxList{idx}) = 0;
res = res | rectMask;
optimize corners function:
function [ corners] = optimizeCorners(xy)
%finds the corners which fits the most for this set of points
Y = xy(:,1);
X = xy(:,2);
%initial corners guess
corners = getInitialCornersGuess(xy);
boundriesIm = zeros(max(Y)+20,max(X)+20);
boundriesIm(sub2ind(size(boundriesIm),xy(:,1),xy(:,2))) = 1;
%R represents the search radius
R = 7;
%continue optimizing as long as there is no change in the final result
unchangedIterations = 0;
while unchangedIterations<4
for ii=1:4
%optimize corner ii
currentCorner = corners(ii,:);
bestCorner = currentCorner;
bestRes = calcEnergy(boundriesIm,corners);
cornersToEvaluate = corners;
for yy=currentCorner(1)-R:currentCorner(1)+R
for xx=currentCorner(2)-R:currentCorner(2)+R
cornersToEvaluate(ii,:) = [yy,xx];
res = calcEnergy(boundriesIm,cornersToEvaluate);
if res > bestRes
bestRes = res;
bestCorner = [yy,xx];
end
end
end
if isequal(bestCorner,currentCorner)
unchangedIterations = unchangedIterations + 1;
else
unchangedIterations = 0;
corners(ii,:) = bestCorner;
end
end
end
end
function res = calcEnergy(boundriesIm,corners)
%calculates the score of the corners list, given the boundries image.
%the result is acutally the jaccard index of the boundries map and the
%lines map
linesMask = drawLines(size(boundriesIm),corners,corners([2:4,1],:));
res = sum(sum(linesMask&boundriesIm)) / sum(sum(linesMask|boundriesIm));
end
get initial corners function:
function corners = getInitialCornersGuess(boundryPnts)
%calculates an initial guess for the 4 corners
%finds corners by performing kmeans on largest curvature pixels
[curvatureArr] = calcCurvature(boundryPnts, 5);
highCurv = boundryPnts(curvatureArr>0.3,:);
[~,C] = kmeans([highCurv(:,1),highCurv(:,2)],4);
%sorts the corners from top to bottom - preprocessing stage
C = int16(C);
corners = zeros(size(C));
%top left corners
topLeftInd = find(sum(C,2)==min(sum(C,2)));
corners(1,:) = C(topLeftInd,:);
%bottom right corners
bottomRightInd = find(sum(C,2)==max(sum(C,2)));
corners(3,:) = C(bottomRightInd,:);
%top right and bottom left corners
C([topLeftInd,bottomRightInd],:) = [];
topRightInd = find(C(:,2)==max(C(:,2)));
corners(4,:) = C(topRightInd,:);
bottomLeftInd = find(C(:,2)==min(C(:,2)));
corners(2,:) = C(bottomLeftInd,:);
end
function [curvatureArr] = calcCurvature(xy, halfWinSize)
%calculate the curvature of a list of points (xy) given a window size
%curvature calculation
curvatureArr = zeros(size(xy,1),1);
for t=1:halfWinSize
y = xy(t:halfWinSize:end,1);
x = xy(t:halfWinSize:end,2);
dx = gradient(x);
ddx = gradient(dx);
dy = gradient(y);
ddy = gradient(dy);
num = abs(dx .* ddy - ddx .* dy) + 0.000001;
denom = dx .* dx + dy .* dy + 0.000001;
denom = sqrt(denom);
denom = denom .* denom .* denom;
curvature = num ./ denom;
%normalizing
if(max(curvature) > 0)
curvature = curvature / max(curvature);
end
curvatureArr(t:halfWinSize:end) = curvature;
end
end
draw lines function:
function mask = drawLines(imgSize, P1, P2)
%generates a mask with lines, determine by P1 and P2 points
mask = zeros(imgSize);
P1 = double(P1);
P2 = double(P2);
for ii=1:size(P1,1)
x1 = P1(ii,2); y1 = P1(ii,1);
x2 = P2(ii,2); y2 = P2(ii,1);
% Distance (in pixels) between the two endpoints
nPoints = ceil(sqrt((x2 - x1).^2 + (y2 - y1).^2));
% Determine x and y locations along the line
xvalues = round(linspace(x1, x2, nPoints));
yvalues = round(linspace(y1, y2, nPoints));
% Replace the relevant values within the mask
mask(sub2ind(size(mask), yvalues, xvalues)) = 1;
end

Non overlapping randomly located circles

I need to generate a fixed number of non-overlapping circles located randomly. I can display circles, in this case 20, located randomly with this piece of code,
for i =1:20
x=0 + (5+5)*rand(1)
y=0 + (5+5)*rand(1)
r=0.5
circle3(x,y,r)
hold on
end
however circles overlap and I would like to avoid this. This was achieved by previous users with Mathematica https://mathematica.stackexchange.com/questions/69649/generate-nonoverlapping-random-circles , but I am using MATLAB and I would like to stick to it.
For reproducibility, this is the function, circle3, I am using to draw the circles
function h = circle3(x,y,r)
d = r*2;
px = x-r;
py = y-r;
h = rectangle('Position',[px py d d],'Curvature',[1,1]);
daspect([1,1,1])
Thank you.
you can save a list of all the previously drawn circles. After
randomizing a new circle check that it doesn't intersects the previously drawn circles.
code example:
nCircles = 20;
circles = zeros(nCircles ,2);
r = 0.5;
for i=1:nCircles
%Flag which holds true whenever a new circle was found
newCircleFound = false;
%loop iteration which runs until finding a circle which doesnt intersect with previous ones
while ~newCircleFound
x = 0 + (5+5)*rand(1);
y = 0 + (5+5)*rand(1);
%calculates distances from previous drawn circles
prevCirclesY = circles(1:i-1,1);
prevCirclesX = circles(1:i-1,2);
distFromPrevCircles = ((prevCirclesX-x).^2+(prevCirclesY-y).^2).^0.5;
%if the distance is not to small - adds the new circle to the list
if i==1 || sum(distFromPrevCircles<=2*r)==0
newCircleFound = true;
circles(i,:) = [y x];
circle3(x,y,r)
end
end
hold on
end
*notice that if the amount of circles is too big relatively to the range in which the x and y coordinates are drawn from, the loop may run infinitely.
in order to avoid it - define this range accordingly (it can be defined as a function of nCircles).
If you're happy with brute-forcing, consider this solution:
N = 60; % number of circles
r = 0.5; % radius
newpt = #() rand([1,2]) * 10; % function to generate a new candidate point
xy = newpt(); % matrix to store XY coordinates
fails = 0; % to avoid looping forever
while size(xy,1) < N
% generate new point and test distance
pt = newpt();
if all(pdist2(xy, pt) > 2*r)
xy = [xy; pt]; % add it
fails = 0; % reset failure counter
else
% increase failure counter,
fails = fails + 1;
% give up if exceeded some threshold
if fails > 1000
error('this is taking too long...');
end
end
end
% plot
plot(xy(:,1), xy(:,2), 'x'), hold on
for i=1:size(xy,1)
circle3(xy(i,1), xy(i,2), r);
end
hold off
Slightly amended code #drorco to make sure exact number of circles I want are drawn
nCircles = 20;
circles = zeros(nCircles ,2);
r = 0.5;
c=0;
for i=1:nCircles
%Flag which holds true whenever a new circle was found
newCircleFound = false;
%loop iteration which runs until finding a circle which doesnt intersect with previous ones
while ~newCircleFound & c<=nCircles
x = 0 + (5+5)*rand(1);
y = 0 + (5+5)*rand(1);
%calculates distances from previous drawn circles
prevCirclesY = circles(1:i-1,1);
prevCirclesX = circles(1:i-1,2);
distFromPrevCircles = ((prevCirclesX-x).^2+(prevCirclesY-y).^2).^0.5;
%if the distance is not to small - adds the new circle to the list
if i==1 || sum(distFromPrevCircles<=2*r)==0
newCircleFound = true;
c=c+1
circles(i,:) = [y x];
circle3(x,y,r)
end
end
hold on
end
Although this is an old post, and because I faced the same problem before I would like to share my solution, which uses anonymous functions: https://github.com/davidnsousa/mcsd/blob/master/mcsd/cells.m . This code allows to create 1, 2 or 3-D cell environments from user-defined cell radii distributions. The purpose was to create a complex environment for monte-carlo simulations of diffusion in biological tissues: https://www.mathworks.com/matlabcentral/fileexchange/67903-davidnsousa-mcsd
A simpler but less flexible version of this code would be the simple case of a 2-D environment. The following creates a space distribution of N randomly positioned and non-overlapping circles with radius R and with minimum distance D from other cells. All packed in a square region of length S.
function C = cells(N, R, D, S)
C = #(x, y, r) 0;
for n=1:N
o = randi(S-R,1,2);
while C(o(1),o(2),2 * R + D) ~= 0
o = randi(S-R,1,2);
end
f = #(x, y) sqrt ((x - o(1)) ^ 2 + (y - o(2)) ^ 2);
c = #(x, y, r) f(x, y) .* (f(x, y) < r);
C = #(x, y, r) + C(x, y, r) + c(x, y, r);
end
C = #(x, y) + C(x, y, R);
end
where the return C is the combined anonymous functions of all circles. Although it is a brute force solution it is fast and elegant, I believe.