How do I project a map from the plane to a sphere?

29 views (last 30 days)
I need to project points from the 2-D plane to a 3-D unit sphere centered at (0,0,0).
The context is Complex Analysis. The goal will be to map any linear fractional map to the sphere. For now I need to understand how Matlab can achieve the more basic projection of a fractal onto the sphere and do the reverse. I know Matlab has a mapping toolbox (that I don't really understand either) and that may be sufficient.
I'm not asking for a step by step process. Just a general direction to what functions and methods might be useful. I hope this question isnt too broad.
The following code creates a fractal image with data stored in the map(i,j) matrix.
----------------------------------------------------------------------------------------------------------------
clear all
clc
clf
res = 0.05;
x = -2:res:2;
y = x';
depth = 32;
grid = zeros(length(x),length(y));
map =zeros(length(x),length(y));
c = 0.30 + 0.5*1i;
for i = 1:length(x)
for j = 1:length(y)
grid(i,j) = x(i)+y(j)*1i;
end
end
for i = 1:length(x)
for j = 1:length(y)
for n = 1:depth
if abs(grid(i,j)) > 2
map(i,j) = n;
break
else
grid(i,j) = grid(i,j)^2 + c;
end
end
end
end
map(map==0) = depth ;
map;
image(map)
axis image
colormap(flipud(jet(depth)))
--------------------------------------------------------------------------------------
The data stored in map(i,j) is what needs to be projected.
Thank you all

Answers (4)

Umar
Umar on 3 Feb 2025
Edited: Umar on 3 Feb 2025

Hi @Christopher Scott,

To achieve the projection of points from a 2-D plane onto a 3-D unit sphere in MATLAB, you can utilize spherical coordinates. The projection can be defined mathematically, where each point in the 2-D plane is transformed into a point on the surface of the sphere. The following steps outline the approach, followed by the updated MATLAB code. The projection of a point ((x, y)) in the 2-D plane onto a unit sphere can be expressed using the following equations:

Convert Cartesian to Spherical Coordinates: The radius (r) of the sphere is 1 (unit sphere).

The azimuthal angle (\theta) can be derived from the x-coordinate: [ theta = frac{x}{sqrt{x^2 + y^2 + 1}} ]

The polar angle (phi) can be derived from the y-coordinate: [ phi = frac{y}{sqrt{x^2 + y^2 + 1}} ]

The z-coordinate is given by: [ z = sqrt{1 - x^2 - y^2} ]

Mapping to the Sphere: The final coordinates on the sphere can be represented as: [ X = r cdot sin(phi) cdot cos(theta) ] [ Y = r cdot \sin(phi) cdot sin(theta) ] [ Z = r cdot cos(phi) ]

Below is the updated MATLAB code that includes the projection of the fractal data onto a 3-D unit sphere. The code retains the original fractal generation logic and adds the projection functionality.

% Fractal generation parameters
res = 0.05;
x = -2:res:2;
y = x';
depth = 32;
grid = zeros(length(x), length(y));
map = zeros(length(x), length(y));
c = 0.30 + 0.5*1i;
% Generate the fractal
for i = 1:length(x)
  for j = 1:length(y)
      grid(i,j) = x(i) + y(j)*1i;
  end
end    
for i = 1:length(x)
  for j = 1:length(y)
      for n = 1:depth
          if abs(grid(i,j)) > 2
              map(i,j) = n;
              break;
          else
              grid(i,j) = grid(i,j)^2 + c;
          end
      end
  end
end
map(map==0) = depth;
% Projection onto the 3D unit sphere
[X, Y, Z] = sphere(50); % Create a unit sphere
hold on;
colormap(flipud(jet(depth)));
% Normalize map values to fit the sphere
for i = 1:length(x)
  for j = 1:length(y)
      % Normalize the coordinates
      norm_factor = sqrt(x(i)^2 + y(j)^2 + 1);
      theta = x(i) / norm_factor;
      phi = y(j) / norm_factor;
        % Calculate the 3D coordinates
        sphere_x = sin(atan2(phi, sqrt(1 - theta^2))) * cos(atan2(theta, sqrt(1 - 
        phi^2)));
        sphere_y = sin(atan2(phi, sqrt(1 - theta^2))) * sin(atan2(theta, sqrt(1 - 
        phi^2)));
        sphere_z = cos(atan2(phi, sqrt(1 - theta^2)));
        % Plot the points on the sphere
        scatter3(sphere_x, sphere_y, sphere_z, 36, map(i,j), 'filled');
    end
  end
% Set the view and axis properties
axis equal;
view(3);
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Projection of Fractal Data onto a 3D Unit Sphere');
hold off;

Please see attached.

The above code provides a comprehensive approach to project points from a 2-D plane onto a 3-D unit sphere in MATLAB. By utilizing spherical coordinates and the built-in plotting functions, you can visualize the fractal data effectively.

1. Fractal Generation: The initial part of the code generates the fractal and stores the results in the map matrix. 2. Sphere Creation: The sphere function creates a unit sphere for visualization. 3. Normalization and Projection: The nested loops iterate through the map matrix, normalizing the coordinates and calculating their corresponding positions on the sphere. 4. Visualization: The scatter3 function is used to plot the projected points on the sphere, with colors corresponding to the values in the map.

If you have further questions or need additional modifications, feel free to ask!

  2 Comments
Christopher Scott
Christopher Scott on 15 Feb 2025
This is excellent. Thank you for your efforts! Im sure this will help many others as well.

Sign in to comment.


Christopher Scott
Christopher Scott on 4 Feb 2025
Thank you for your indepth response! Im trying to understand why the code you added has errors. Both of these expressions
sqrt(1 - phi^2)));
for sphere_x and sphere_y have red marks under the minus sign and and the first ")"
Ill see if I can debug it.
Again tank you!
  3 Comments
Umar
Umar on 5 Feb 2025

Hi @ Christopher Scott,

Please let me know how can I help you further or help you clarify any issues.

Image Analyst
Image Analyst on 15 Feb 2025
@Christopher Scott if you need the other (bottom) half of the sphere, I guess you could just plot the negative of the z values. And you could try to see if "axis equal" will change the z scaling to make it more sphere-like.

Sign in to comment.


Christopher Scott
Christopher Scott on 8 Feb 2025
I have been trying other methods in addition to the above code and am still unable to project the plane onto the entire unit sphere. Ultimately it should look like a colorful ball.
Are there any other suggestions?
  5 Comments
Image Analyst
Image Analyst on 9 Feb 2025
Well, maybe try again because I used two different browsers and can't see what you tried to upload. This is what I see:
Umar
Umar on 9 Feb 2025

Hi @Christopher Scott,

I went through analysis of my recent code and your code again, it retains your original fractal generation logic while adding functionality for projecting these points onto the sphere.

   clear all
   clc
   clf
   % Parameters
   res = 0.05;               % Resolution
   x = -2:res:2;            % X range
   y = x';                  % Y range (transpose)
   depth = 32;              % Iteration depth
   grid = zeros(length(x), length(y));
   map = zeros(length(x), length(y));
   c = 0.30 + 0.5*1i;      % Complex parameter
   % Generate grid of complex numbers
   for i = 1:length(x)
    for j = 1:length(y)
        grid(i,j) = x(i) + y(j)*1i;
    end
  end    
   % Fractal generation using iteration
   for i = 1:length(x)
    for j = 1:length(y)
        for n = 1:depth
            if abs(grid(i,j)) > 2
                map(i,j) = n;
                break;
            else
                grid(i,j) = grid(i,j)^2 + c;
            end
        end
    end
  end
   map(map==0) = depth; % Set unassigned points to max depth
% Projection onto a 3D unit sphere
 [x_sphere, y_sphere, z_sphere] = sphere(50); % Create a unit sphere 
 mesh
   % Prepare figure for fractal and sphere projection
   figure;
   % Plotting the fractal image on a flat surface
   subplot(1, 2, 1);
   image(map);
   axis image;
   colormap(flipud(jet(depth)));
   title('Fractal Image');
   % Plotting the projected points on the sphere
   subplot(1, 2, 2);
   hold on;
   % Map each point from the fractal to the sphere
   for i = 1:length(x)
    for j = 1:length(y)
        if map(i,j) < depth   % Only plot points that were iterated over
            r = sqrt(x(i)^2 + y(j)^2);
            theta = atan2(y(j), x(i));
            phi = acos(r / sqrt(r^2 + 1)); 
            % Calculate angle from vertical
            % Spherical coordinates conversion to Cartesian coordinates
            X = sin(phi) * cos(theta);
            Y = sin(phi) * sin(theta);
            Z = cos(phi);
            plot3(X, Y, Z, '.', 'MarkerSize', map(i,j)/depth*10); %             Scale marker size by depth
        end
    end
  end
   % Add sphere surface for reference
   surf(x_sphere, y_sphere, z_sphere, 'FaceAlpha', 0.3); 
   % Transparent sphere    surface
   axis equal;
   title('Projection onto Unit Sphere');
   xlabel('X-axis');
   ylabel('Y-axis');
   zlabel('Z-axis');
   grid on;
   hold off;

Please see attached.

Visualization: This updated code provides side-by-side visualization of both the fractal image and its projection onto a unit sphere. This helps in understanding how complex plane data maps into three dimensions.

This approach should provide you with a solid foundation for projecting your fractal data onto a sphere and visualizing it effectively in MATLAB.

Hope this helps now.

Sign in to comment.


Image Analyst
Image Analyst on 8 Feb 2025
Here is a demo for how to map an image onto a 2.5-D surface. The surface doesn't go all the way around in 3-D though.
% Demo to create a surface from a gray scale image and have the coloration of the surface taken from a different RGB image.
clc; % Clear the command window.
clear all;
close all;
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 15;
fprintf('Beginning to run %s.m ...\n', mfilename);
%===============================================================================
% Get the name of the demo image the user wants to use.
% Let's let the user select from a list of all the demo images that ship with the Image Processing Toolbox.
folder = fileparts(which('cameraman.tif')); % Determine where demo folder is (works with all versions).
% Demo images have extensions of TIF, PNG, and JPG. Get a list of all of them.
imageFiles = [dir(fullfile(folder,'*.TIF')); dir(fullfile(folder,'*.PNG')); dir(fullfile(folder,'*.jpg'))];
for k = 1 : length(imageFiles)
% fprintf('%d: %s\n', k, files(k).name);
[~, baseFileName, extension] = fileparts(imageFiles(k).name);
ca{k} = [baseFileName, extension];
end
% Sort the base file names alphabetically.
[ca, sortOrder] = sort(ca);
imageFiles = imageFiles(sortOrder);
button = menu('Use which demo image?', ca); % Display all image file names in a popup menu.
% Get the base filename.
baseFileName = imageFiles(button).name; % Assign the one on the button that they clicked on.
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% img = imread('pears.png');
rgbImage = imread(fullFileName);
[rows, colummns, numberOfColorChannels] = size(rgbImage)
subplot(2, 2, 1);
imshow(rgbImage);
axis('on', 'image');
impixelinfo; % Let user mouse around and get RGB or gray levels.
caption = sprintf('Original Image (Source of Colors) : %s', baseFileName);
title(caption, 'FontSize', fontSize);
% Make gray scale value image.
peaksImage = flipud(peaks(100));
subplot(2, 2, 3);
imshow(peaksImage, []);
axis('on', 'image');
impixelinfo; % Let user mouse around and get RGB or gray levels.
title('Gray Scale Image of Z (height, elevation) Values: Peaks(100)', 'FontSize', fontSize);
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
% Apply the RGB image as a texture to the surface.
subplot(2, 2, [2,4]);
surf(peaksImage, ...
'FaceColor', 'texturemap',...
'EdgeColor', 'none',...
'Cdata', rgbImage);
view(3);
axis ij;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
zlabel('Z', 'FontSize', fontSize);
if numberOfColorChannels == 1
colorbar;
end
title('Peaks Image with "Original" Image Applied as a "texturemap"', 'FontSize', fontSize);
g = gcf;
g.WindowState = 'maximized'

Categories

Find more on Fractals in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!