How can I convert a svg file to matrix or image in Matlab?
21 views (last 30 days)
Show older comments
Simone Cotta Ramusino
on 3 Nov 2022
Commented: Simone Cotta Ramusino
on 6 Nov 2022
I have a .svg file containing the slicing of a model. How can I import and read the slices in Matlab? They are binary slices and I need to loop over each of them to obtain the corresponding matrix. I'd rather not use Exchange functions, but that is not mandatory.
3 Comments
Accepted Answer
DGM
on 4 Nov 2022
If you have raster images embedded in an SVG file, you may be able to extract them something like this:
% filename of svg file
fname = 'multiobject.svg.fakeextension.txt';
% extract image extensions and data from file
% ignore all other objects in the file
str = fileread(fname);
blockinfo = regexp(str,'data:image/(.*?);base64,([^"]*)','tokens');
for k = 1:numel(blockinfo)
% get the info for this image
thisext = blockinfo{k}{1};
thisdata = blockinfo{k}{2};
% decode the image file
thisdata = matlab.net.base64decode(thisdata);
% write the file using the original format extension
fname = sprintf('myextractedfile_%04d.%s',k,thisext);
fid = fopen(fname,'w');
fwrite(fid,thisdata,'uint8');
fclose(fid);
end
Now all the files can simply be read from disk.
A = imread('myextractedfile_0001.png');
imshow(A)
Without knowing what exactly is in the file, I can't know for sure if that's what you need.
13 Comments
DGM
on 6 Nov 2022
Yeah, I basically looked at the file and assumed that other files generated by the same software would have the same formatting. Unless slic3r happens to add something other than polygon objects to some files, I tentatively assume that it should work. That's an approximation based on a single observation.
Swapping images.roi.Polygon() with images.roi.Freehand() doesn't really change anything, since their position properties are compatibly-oriented. The only real difference between the two is in how they're created when doing so interactively (with the mouse). Since they're being used programmatically, they behave the same.
Yes, I suppose you could rewrite it that way as well. I just saw potential value in knowing the factors which map between part geometry and image geometry. That, and it's a bit of a holdover from the prior code. You're free to adapt it however you feel suits your needs.
More Answers (0)
See Also
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!