Reputation: 663
Problem : The image loses its transparency when plot using surf
I have already figured out how to create a png file with a transparent background as described in numerous other threads.here
However, when plot using surf.m, the image is not transparent
Here is the code that I have so far:
img = imread('image.png');
A1 = ones(size(img));A2 = ones(size(img));A3 = ones(size(img));
A1(img(:,:,1)==0)=0;A2(img(:,:,2)==0)=0;A3(img(:,:,3)==0)=0;
A = A1+A2+A3;
A= A(:,:,1);
imwrite(img,'test.png','alpha',A);
[img,map,alpha] = imread('test.png');
ximage = [-.5,.5;-.5,.5];
yimage = [0,0;0,0];
zimage = [.5,.5;-.5,-.5];
surf(ximage,yimage,zimage,'Cdata',img,'Facecolor','texturemap','Edgecolor','none','alphadata',alpha);
axis vis3d
The code converts image.png (blue square) to a test.png with a transparent background (get rid of the black background). test.png is then used to generate a surf plot which turns out to be not transparent. Any idea what I am doing wrong?
Upvotes: 3
Views: 4021
Reputation: 3563
There is a function called alpha
in MATLAB which sets transparency for the objects in current axes. I suggest to change the variable named alpha
to another name by replacing the following line
[img,map,alpha] = imread('test.png');
to
[img,map,alphaChannel] = imread('test.png');
Now, after running surf
, you can set the transparency for your plot through alpha
function.
Using alpha
function
surf(ximage,yimage,zimage,'Cdata',img,'Facecolor','texturemap','Edgecolor', ...
'none','alphadata',alpha);
alpha(0.5); %# line added
axis vis3d
Using surf
function
If you want to set the transparency through the surf
function, you need to add 'FaceAlpha'
parameter:
surf(ximage,yimage,zimage,'Cdata',img,'Facecolor','texturemap','Edgecolor', ...
'none','AlphaData',alphaChannel,'FaceAlpha',0.5);
Result
More information about alpha
and surf
functions.
But those functions above sets the transparency for the entire plot. If you want to set your original matrix of transparency, you need to pass 'FaceAlpha','texture'
parameter to surf
:
handler = surf( ximage , yimage , zimage , 'Cdata', img , ...
'FaceColor','texturemap', ...
'EdgeColor','none', ...
'FaceAlpha','texture', ...
'AlphaData', alphaChannel);
axis vis3d
Result
More details. Hope it helps!
Upvotes: 3