How to find and highlight the brightest region an image in Matlab? - matlab

Dears,
I would like to kindly ask you for support. My goal is to find the brightest region of the RGB image and highlight it without additional tools. Please see my example below.
rgbImage = imread( 'Zoom1_WhiteImage.png' );
imshow(rgbImage);
[rows, columns, numberOfColorChannels] = size(rgbImage)
[x, y] = meshgrid(1:columns, 1:rows);
% Extract the individual red, green, and blue color channels.
% Need to cast to double or else x and y will be clipped to 255 when we concatenate them.
if numberOfColorChannels == 1
% Leave as gray scale.
% Get array listing [r, g, b, x, y]. Using (:) will turn all the 2-D arrays into column vectors.
output = [rgbImage(:), x(:), y(:)];
else
redChannel = double(rgbImage(:, :, 1));
greenChannel = double(rgbImage(:, :, 2));
blueChannel = double(rgbImage(:, :, 3));
% Get array listing [r, g, b, x, y]. Using (:) will turn all the 2-D arrays into column vectors.
output = [redChannel(:), greenChannel(:), blueChannel(:), x(:), y(:)];
end
[rows, columns] = find(rgbImage == 155);
imshow(rgbImage);
hold on
Unfortunately, I am struggling with how to proceed with the plot of the points that should overlay the grey image.
Would you be so kind and help me to finish the code, please?

I'd recommend you read about logical indexing in MATLAB - it's a very powerful concept, and it allows you to skip most of the things you're trying to do by flattening the arrays, and creating separate arrays of indices with meshgrid. Here is an article that addresses logical indexing down at the bottom, for example.
I've modified and added to your code so it accomplishes the job using logical indexing. I tested this in R2019b.
rgbImage = imread( 'Zoom1_WhiteImage.png' );
imshow(rgbImage);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% This is unnecessary - the 'find' command will generate the indices
% without you preparing a matrix of them:
% [x, y] = meshgrid(1:columns, 1:rows);
if numberOfColorChannels == 1
% No need to flatten the image, or combine it with indices:
%output = [rgbImage(:), x(:), y(:)];
brightness = rgbImage; % For a 1 channel image, brightness is the same as the original pixel value.
else
% redChannel = double(rgbImage(:, :, 1));
% greenChannel = double(rgbImage(:, :, 2));
% blueChannel = double(rgbImage(:, :, 3));
% Get array listing [r, g, b, x, y]. Using (:) will turn all the 2-D arrays into column vectors.
% output = [redChannel(:), greenChannel(:), blueChannel(:), x(:), y(:)];
% For an RGB image, the brightness can be estimated in various ways, here's one standard formula:
brightness = (0.2126*rgbImage(:, :, 1) + 0.7152*rgbImage(:, :, 2) + 0.0722*rgbImage(:, :, 3));
end
% Establish a brightness threshold - pixels brighter than this value will
% be highlighted
threshold = 215;
% Create a zero-filled mask of equal size to the image to hold the
% information of which pixels met the brightness criterion:
mask = zeros(rows, columns, 'logical');
% Assign "1" to any mask pixels whose corresponding image pixel met the
% brightness criterion:
mask(brightness > threshold) = 1;
figure;
% Overlay and display mask. imoverlay was introduced in R2017, but the
% syntax has changed a bit, so check the version you're using. You can also
% use imfuse, or imshowpair, or make your own image blending algorithm,
% depending on how you want it to look.
imshow(imoverlay(rgbImage, mask, 'red'));
hold on

Related

matlab quiver3 plot color gradient in z direction? [duplicate]

I want the color of each arrow in a quiver3 plot from MATLAB to correspond to the magnitude of each arrow. Is there any way to do that?
I saw a few examples online that are able to do this for the 2D quiver, however none of them work for the 3D variant, quiver3.
I have the following plot and want to replace the blue arrows with a color corresponding to their magnitude.
In the old graphics system (R2014a and earlier) this is not possible using the built-in quiver object. You can easily get all of the plot objects that are used to compose the quiver plot
q = quiver(1:5, 1:5, 1:5, 1:5);
handles = findall(q, 'type', 'line');
But the tails are all represented by one plot object, and the arrow heads are represented by another. As such, you can't alter the color of each head/tail individually.
set(handles(1), 'Color', 'r')
set(handles(2), 'Color', 'g')
However, with the introduction of HG2 (R2014b and later), you can actually get access to two (undocumented) LineStrip objects (matlab.graphics.primitive.world.LineStrip) (one represents the heads and one represents the tails). These are accessible via the hidden properties Tail and Head.
q = quiver(1, 1, 1, 1);
headLineStrip = q.Head;
tailLineStrip = q.Tail;
You can then alter the color properties of these objects to make each arrow a different color.
The Basic Idea
To do this, I first compute the magnitude of all quiver arrows (this works for both quiver and quiver3)
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
Then I use the current colormap to map each magnitude to an RGB value. The shortest arrow is assigned the lowest color on the colormap and the longest arrow is assigned the highest color on the colormap. histcounts works great for assigning each magnitude an index which can be passed to ind2rgb along with the colormap itself. We have to multiply by 255 because we need the color to be RGB as an 8-bit integer.
% Get the current colormap
currentColormap = colormap(gca);
% Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
% Now map this to a colormap
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
The LineStrip ColorData property (when specified as truecolor) also needs to have an alpha channel (which we will set to 255 meaning opaque).
cmap(:,:,4) = 255;
At this point we can then set the ColorBinding property to interpolated rather than object (to decouple it from the quiver object) and set the ColorData property of both q.Head and q.Tail to the colors we created above giving each arrow it's own color.
Full Solution
NOTE: This solution works for both quiver and quiver3 and the code does not have to be adapted at all.
%// Create a quiver3 as we normally would (could also be 2D quiver)
x = 1:10;
y = 1:10;
[X,Y] = meshgrid(x, y);
Z = zeros(size(X));
U = zeros(size(X));
V = zeros(size(X));
W = sqrt(X.^2 + Y.^2);
q = quiver3(X, Y, Z, U, V, W);
%// Compute the magnitude of the vectors
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
%// Get the current colormap
currentColormap = colormap(gca);
%// Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
%// Now map this to a colormap to get RGB
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
cmap(:,:,4) = 255;
cmap = permute(repmat(cmap, [1 3 1]), [2 1 3]);
%// We repeat each color 3 times (using 1:3 below) because each arrow has 3 vertices
set(q.Head, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:3,:,:), [], 4).'); %'
%// We repeat each color 2 times (using 1:2 below) because each tail has 2 vertices
set(q.Tail, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:2,:,:), [], 4).');
And applied to a 2D quiver object
If you don't necessarily want to scale the arrows to the entire range of the colormap you could use the following call to histcounts (instead of the line above) to map the magnitudes using the color limits of the axes.
clims = num2cell(get(gca, 'clim'));
[~, ~, ind] = histcounts(mags, linspace(clims{:}, size(currentColormap, 1)));
If your using a post r2014b version you can use undocumented features to change the colour of each line and head:
figure
[x,y] = meshgrid(-2:.5:2,-1:.5:1);
z = x .* exp(-x.^2 - y.^2);
[u,v,w] = surfnorm(x,y,z);
h=quiver3(x,y,z,u,v,w);
s = size(x);
nPoints = s(1)*s(2);
% create a colour map
cmap = parula(nPoints);
% x2 because each point has 2 points, a start and an end.
cd = uint8(repmat([255 0 0 255]', 1, nPoints*2));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the start and end of the
% line.
for jj=1:2
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the tail
set(h.Tail, 'ColorBinding','interpolated', 'ColorData',cd)
% create a color matrix for the heads
cd = uint8(repmat([255 0 0 255]', 1, nPoints*3));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the all the points
% at the head of the arrow
for jj=1:3
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the head
set(h.Head, 'ColorBinding','interpolated', 'ColorData',cd)
Note: I've not done anything clever with the magnitude and simply change the colour of each quiver based on the order in the original matrix - but you should be able to get the idea on how to use this "feature"
Note that if you are using Suevers solution and have NaNs in your data you should include this line before calling histcounts:
mags(isnan(mags)) = [];
Otherwise you will get an error about wrong input size because matlab does not create vertices for NaNs in your U/V/W data.

Plotting normals (quivers) with individual color [duplicate]

I want the color of each arrow in a quiver3 plot from MATLAB to correspond to the magnitude of each arrow. Is there any way to do that?
I saw a few examples online that are able to do this for the 2D quiver, however none of them work for the 3D variant, quiver3.
I have the following plot and want to replace the blue arrows with a color corresponding to their magnitude.
In the old graphics system (R2014a and earlier) this is not possible using the built-in quiver object. You can easily get all of the plot objects that are used to compose the quiver plot
q = quiver(1:5, 1:5, 1:5, 1:5);
handles = findall(q, 'type', 'line');
But the tails are all represented by one plot object, and the arrow heads are represented by another. As such, you can't alter the color of each head/tail individually.
set(handles(1), 'Color', 'r')
set(handles(2), 'Color', 'g')
However, with the introduction of HG2 (R2014b and later), you can actually get access to two (undocumented) LineStrip objects (matlab.graphics.primitive.world.LineStrip) (one represents the heads and one represents the tails). These are accessible via the hidden properties Tail and Head.
q = quiver(1, 1, 1, 1);
headLineStrip = q.Head;
tailLineStrip = q.Tail;
You can then alter the color properties of these objects to make each arrow a different color.
The Basic Idea
To do this, I first compute the magnitude of all quiver arrows (this works for both quiver and quiver3)
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
Then I use the current colormap to map each magnitude to an RGB value. The shortest arrow is assigned the lowest color on the colormap and the longest arrow is assigned the highest color on the colormap. histcounts works great for assigning each magnitude an index which can be passed to ind2rgb along with the colormap itself. We have to multiply by 255 because we need the color to be RGB as an 8-bit integer.
% Get the current colormap
currentColormap = colormap(gca);
% Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
% Now map this to a colormap
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
The LineStrip ColorData property (when specified as truecolor) also needs to have an alpha channel (which we will set to 255 meaning opaque).
cmap(:,:,4) = 255;
At this point we can then set the ColorBinding property to interpolated rather than object (to decouple it from the quiver object) and set the ColorData property of both q.Head and q.Tail to the colors we created above giving each arrow it's own color.
Full Solution
NOTE: This solution works for both quiver and quiver3 and the code does not have to be adapted at all.
%// Create a quiver3 as we normally would (could also be 2D quiver)
x = 1:10;
y = 1:10;
[X,Y] = meshgrid(x, y);
Z = zeros(size(X));
U = zeros(size(X));
V = zeros(size(X));
W = sqrt(X.^2 + Y.^2);
q = quiver3(X, Y, Z, U, V, W);
%// Compute the magnitude of the vectors
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
%// Get the current colormap
currentColormap = colormap(gca);
%// Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
%// Now map this to a colormap to get RGB
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
cmap(:,:,4) = 255;
cmap = permute(repmat(cmap, [1 3 1]), [2 1 3]);
%// We repeat each color 3 times (using 1:3 below) because each arrow has 3 vertices
set(q.Head, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:3,:,:), [], 4).'); %'
%// We repeat each color 2 times (using 1:2 below) because each tail has 2 vertices
set(q.Tail, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:2,:,:), [], 4).');
And applied to a 2D quiver object
If you don't necessarily want to scale the arrows to the entire range of the colormap you could use the following call to histcounts (instead of the line above) to map the magnitudes using the color limits of the axes.
clims = num2cell(get(gca, 'clim'));
[~, ~, ind] = histcounts(mags, linspace(clims{:}, size(currentColormap, 1)));
If your using a post r2014b version you can use undocumented features to change the colour of each line and head:
figure
[x,y] = meshgrid(-2:.5:2,-1:.5:1);
z = x .* exp(-x.^2 - y.^2);
[u,v,w] = surfnorm(x,y,z);
h=quiver3(x,y,z,u,v,w);
s = size(x);
nPoints = s(1)*s(2);
% create a colour map
cmap = parula(nPoints);
% x2 because each point has 2 points, a start and an end.
cd = uint8(repmat([255 0 0 255]', 1, nPoints*2));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the start and end of the
% line.
for jj=1:2
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the tail
set(h.Tail, 'ColorBinding','interpolated', 'ColorData',cd)
% create a color matrix for the heads
cd = uint8(repmat([255 0 0 255]', 1, nPoints*3));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the all the points
% at the head of the arrow
for jj=1:3
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the head
set(h.Head, 'ColorBinding','interpolated', 'ColorData',cd)
Note: I've not done anything clever with the magnitude and simply change the colour of each quiver based on the order in the original matrix - but you should be able to get the idea on how to use this "feature"
Note that if you are using Suevers solution and have NaNs in your data you should include this line before calling histcounts:
mags(isnan(mags)) = [];
Otherwise you will get an error about wrong input size because matlab does not create vertices for NaNs in your U/V/W data.

extracting contents and calculating area within an image

Objective :
I need to extract and highlight a specific color from a given image[Say X] and finally I need to calculate the Area of X.
I need help in :
Detecting individual labels in the image[below] in form of a circle.
What I have done :
Below is my code and I have attached the RGB variable's image[below]. I have extracted the "beige color" from the given image(that is X) and labeled it.
To detect the individual component, I tried like the classical "Coins Example [Identifying different coin values from an image using MATLAB", to first detect element. But here as the regions are not uniform, So, I am bit confused.
Code :
clear all; clc;
close all;
I = imread('19.jpg');
%figure;imshow(I);
B = White_Beige(I); // The Function is used to threshold the RGB image
to LAB colorspace. Here, we extract the Beige
color present in the image and provide the final
Black and White image with the presence of Beige
color as Black and rest as white.
%figure; imshow(B);
BW2 = imfill(~B,'holes');
figure; imshow(BW2);
Border = imclearborder(BW2);
[OBL,nbOBObjets] = bwlabel(Border,8);
RGB = label2rgb(OBL,'jet',[0 0 0]);
figure, imshow(RGB);
Any help is much appreciated
maybe this will help:
Note that in this code the "area" occupied by a color is represented as a real number on the interval (0, 1), where 0 means no pixel in the image is that color, and 1 means that all of the pixels in the image are that color.
[A, map] = imread('L8IZU_2.png');
image(A); % display the image
if ~isempty(map)
A = ind2rgb(X, map); % convert image to RGB
end
color_counts = zeros(256, 256, 256);
% color_counts(x, y, z) records the number of pixels in the image
% which have RGB color [x-1, y-1, z-1];
% For example color_counts(1, 1, 1) records the number of pixels in
% the image which have color [0, 0, 0];
% As another example, color_counts(65, 43, 11) records the number of
% pixels in the image which are of color [64, 42, 10];
time_of_last_progress_report = clock;
% traverse the image pixel by pixel
for m = 1:size(A, 1)
for n = 1:size(A, 2)
current_time = clock;
if etime(current_time, time_of_last_progress_report) > 2
percent_progress = 100*(((m - 1)*size(A, 2) + n)/(size(A, 1)*size(A, 2)));
disp(strcat(num2str(percent_progress),'% of the image has been scanned'));
time_of_last_progress_report = clock;
end
current_color = A(m, n, :);
current_color = squeeze(current_color);
% squeeze removes singleton dimensions
% in other words, squeeze converts current_color from a 1x1x3 array into
% a 3x1 array
index = current_color + uint8(ones(size(current_color)));
% Let us say that index = [1, 3, 4];
% We want to increment color_counts(1, 3, 4);
% However, color_counts([1, 3, 4]), or color_counts(index),
% does not return a reference to one single element at that location
% Instead, color_counts([1, 3, 4]) returns a 1x3 vector containing
% the 1st, 3rd, and 4th elements of the color_counts array
% we convert index into a cell array and then convert the cell
% array into a comma separated list.
index2 = num2cell(index);
old_count = color_counts(index2{:});
color_counts(index2{:}) = 1 + old_count;
end
end
disp(' ');% line break
disp('Now sorting colors by how often they apeared....');
color_counts_linear = reshape(color_counts, 1, numel(color_counts));
[color_counts_sorted, indicies] = sort(color_counts_linear, 'descend');
[R,G,B] = ind2sub(size(color_counts),indicies);
R = R - ones(size(R));
G = G - ones(size(G));
B = B - ones(size(B));
areas = (1/(size(A, 1)*size(A, 2))) * color_counts_sorted;
% display the top 5 most common colors
disp(' '); % line break
disp('Top 5 most common colors:');
for k = 1:min(5, numel(areas))
disp(strcat('[', num2str(R(k)), ',', num2str(B(k)), ',', num2str(G(k)),'] : ', num2str(100*areas(k)), '%'));
end

quiver3 arrow color corresponding to magnitude

I want the color of each arrow in a quiver3 plot from MATLAB to correspond to the magnitude of each arrow. Is there any way to do that?
I saw a few examples online that are able to do this for the 2D quiver, however none of them work for the 3D variant, quiver3.
I have the following plot and want to replace the blue arrows with a color corresponding to their magnitude.
In the old graphics system (R2014a and earlier) this is not possible using the built-in quiver object. You can easily get all of the plot objects that are used to compose the quiver plot
q = quiver(1:5, 1:5, 1:5, 1:5);
handles = findall(q, 'type', 'line');
But the tails are all represented by one plot object, and the arrow heads are represented by another. As such, you can't alter the color of each head/tail individually.
set(handles(1), 'Color', 'r')
set(handles(2), 'Color', 'g')
However, with the introduction of HG2 (R2014b and later), you can actually get access to two (undocumented) LineStrip objects (matlab.graphics.primitive.world.LineStrip) (one represents the heads and one represents the tails). These are accessible via the hidden properties Tail and Head.
q = quiver(1, 1, 1, 1);
headLineStrip = q.Head;
tailLineStrip = q.Tail;
You can then alter the color properties of these objects to make each arrow a different color.
The Basic Idea
To do this, I first compute the magnitude of all quiver arrows (this works for both quiver and quiver3)
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
Then I use the current colormap to map each magnitude to an RGB value. The shortest arrow is assigned the lowest color on the colormap and the longest arrow is assigned the highest color on the colormap. histcounts works great for assigning each magnitude an index which can be passed to ind2rgb along with the colormap itself. We have to multiply by 255 because we need the color to be RGB as an 8-bit integer.
% Get the current colormap
currentColormap = colormap(gca);
% Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
% Now map this to a colormap
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
The LineStrip ColorData property (when specified as truecolor) also needs to have an alpha channel (which we will set to 255 meaning opaque).
cmap(:,:,4) = 255;
At this point we can then set the ColorBinding property to interpolated rather than object (to decouple it from the quiver object) and set the ColorData property of both q.Head and q.Tail to the colors we created above giving each arrow it's own color.
Full Solution
NOTE: This solution works for both quiver and quiver3 and the code does not have to be adapted at all.
%// Create a quiver3 as we normally would (could also be 2D quiver)
x = 1:10;
y = 1:10;
[X,Y] = meshgrid(x, y);
Z = zeros(size(X));
U = zeros(size(X));
V = zeros(size(X));
W = sqrt(X.^2 + Y.^2);
q = quiver3(X, Y, Z, U, V, W);
%// Compute the magnitude of the vectors
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
%// Get the current colormap
currentColormap = colormap(gca);
%// Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
%// Now map this to a colormap to get RGB
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
cmap(:,:,4) = 255;
cmap = permute(repmat(cmap, [1 3 1]), [2 1 3]);
%// We repeat each color 3 times (using 1:3 below) because each arrow has 3 vertices
set(q.Head, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:3,:,:), [], 4).'); %'
%// We repeat each color 2 times (using 1:2 below) because each tail has 2 vertices
set(q.Tail, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:2,:,:), [], 4).');
And applied to a 2D quiver object
If you don't necessarily want to scale the arrows to the entire range of the colormap you could use the following call to histcounts (instead of the line above) to map the magnitudes using the color limits of the axes.
clims = num2cell(get(gca, 'clim'));
[~, ~, ind] = histcounts(mags, linspace(clims{:}, size(currentColormap, 1)));
If your using a post r2014b version you can use undocumented features to change the colour of each line and head:
figure
[x,y] = meshgrid(-2:.5:2,-1:.5:1);
z = x .* exp(-x.^2 - y.^2);
[u,v,w] = surfnorm(x,y,z);
h=quiver3(x,y,z,u,v,w);
s = size(x);
nPoints = s(1)*s(2);
% create a colour map
cmap = parula(nPoints);
% x2 because each point has 2 points, a start and an end.
cd = uint8(repmat([255 0 0 255]', 1, nPoints*2));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the start and end of the
% line.
for jj=1:2
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the tail
set(h.Tail, 'ColorBinding','interpolated', 'ColorData',cd)
% create a color matrix for the heads
cd = uint8(repmat([255 0 0 255]', 1, nPoints*3));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
% and we need to assign a colour to the all the points
% at the head of the arrow
for jj=1:3
count = count + 1;
cd(1:3,count) = uint8(255*cmap(ii,:)');
end
end
% set the colour binding method and the colour data of the head
set(h.Head, 'ColorBinding','interpolated', 'ColorData',cd)
Note: I've not done anything clever with the magnitude and simply change the colour of each quiver based on the order in the original matrix - but you should be able to get the idea on how to use this "feature"
Note that if you are using Suevers solution and have NaNs in your data you should include this line before calling histcounts:
mags(isnan(mags)) = [];
Otherwise you will get an error about wrong input size because matlab does not create vertices for NaNs in your U/V/W data.

Most efficient way to draw a bunch of 3d lines in matlab

I need to plot a list of 3d lines in matlab. What is the quickest way to do that?
I am currently doing something like
%edges is a MX2 matrix, holding the list of edges
%points are the vertices' coordinates
hold on; %so all the lines will be saved
for i=1:size(edges,1)
a=edges(i,1); %get first point's index
b=edges(i,2); %get second point's index
p=[points(:,a) points(:,b)]; %construct a 3X2 matrix out of the 2 points
plot3(p(1,:),p(2,:),p(3,:)); %plot a line
end
But this is not only slow during the actual loop, but also at the end, the resulting plot is very slow and irresponsive when I try to, for instance, rotate it using the drag & rotate tool.
I know the same plot using opengl etc would run much faster...
You can use the LINE low-level function, using NaN to plot as separate segments:
%# sample graph vertices and edges (similar to your data)
[adj,XYZ] = bucky;
[r c] = find(adj);
edges = [r c]; %# M-by-2 matrix holding the vertex indices
points = XYZ'; %# 3-by-N matrix of points X/Y/Z coordinates
%# build a list of separated lines
e = edges';
e(end+1,:) = 1;
e = e(:);
p = points(:,e);
p(:,3:3:end) = NaN;
figure
h = line(p(1,:), p(2,:), p(3,:));
view(3)
This is very efficient as it creates a single line object. Now you can customize the line, but it is restricted to have one color for the entire thing:
set(h, 'Color',[.4 .4 1], 'Marker','.', 'MarkerSize',10, ...
'MarkerFaceColor','g', 'MarkerEdgeColor','g')
According to the comments, if you want to have each edge in your graph in a specified color, consider the following code instead. It involves using the SURFACE function:
p = p'; %'# transpose the above p for convenience
clr = (1:size(p,1))'; %'# for each edge, color index in current colormap
figure
surface(p(:,[1 1]), p(:,[2 2]), p(:,[3 3]), [clr clr], ...
'EdgeColor','flat', 'FaceColor','none')
colormap( hsv(numel(clr)) ) %# specify your colormap here
view(3)
I think you can do something like this (caution - brain compiled code...)
figure;
patch('faces', edges, 'vertices', points, 'edgecolor', 'b');
axis equal;
Where edges should be an Nx2 matrix of indices and points should be an Mx3 matrix of coordinates (the transpose of your points array).
From my experience, calling patch directly can be significantly faster than repeated calls to plot.
To give some idea, the times to generate 1000 randomly generated line segments, using my (admittedly old!) MATLAB 7.1 are as follows:
Calling patch: 0.03 seconds.
Calling plot: 0.5 seconds.
EDIT: One way to get the edge colour behaving as you want (specifying a single colour per edge) is to introduce duplicate vertices as follows:
This works-around the issue that the edge colour can only be specified indirectly via vertex colour data. If we were to rely only on the vertex colours then all edges sharing a common vertex might end up with the colour assigned to that vertex - check out the 'flat 'edgecolour description here.
%% a "star" shape, so that we can really see what's going on
%% with the edge colours!!
pp = [0,0,0; 1,-1,0; 1,1,0; -1,1,0; -1,-1,0];
ee = [1,2; 1,3; 1,4; 1,5];
%% important - only 1 colour known per edge, not per vertex!!
cc = (1:size(ee,1))';
%% setup a new set of vertices/edges/colours with duplicate vertices
%% so that each edge gets it's correct colour
nnum = 0;
pnew = zeros(2 * size(ee, 1), 3); %% new vertices
enew = zeros(1 * size(ee, 1), 2); %% new edge indices
cnew = zeros(2 * size(ee, 1), 1); %% new edge colours - via vertices
for j = 1 : size(ee, 1)
n1 = ee(j, 1); %% old edge indices
n2 = ee(j, 2);
enew(j, 1) = nnum + 1; %% new edge indicies into pnew
enew(j, 2) = nnum + 2;
pnew(nnum + 1, :) = pp(n1, :); %% create duplicate vertices
pnew(nnum + 2, :) = pp(n2, :);
cnew(nnum + 1) = cc(j); %% map single edge colour onto both vertices
cnew(nnum + 2) = cc(j);
nnum = nnum + 2;
end
%% Draw the set efficiently via patch
tic
figure;
hold on;
patch('faces', enew, 'vertices', pnew, 'facevertexcdata', cnew, ...
'edgecolor', 'flat', 'facecolor', 'none');
plot(pnew(:,1), pnew(:,2), 'b.');
axis equal;
toc
It would be nicer if MATLAB allowed you to directly specify the edge colour data - but it doesn't seem to support that...
Hope this helps.