Adding to MATLAB gif images using imwrite() (white images beyond certain point) - image

I've tried finding the answer to this all over the place, but I've had no luck so far. You see, I've ran into a problem where I'm generating gif files by appending images into a single gif using a for loop. But after a while, imwrite seems to stop actually adding the images into the gif file - it just adds white spaces instead.
So, the file itself is large enough (250MB) to feasibly have the right number of images in, but when I open it and play it, once it gets past a certain point I just have white images. I'm pretty damn sure it's nothing to do with the for loop itself - I've had it print out the image file it's working on for each loop iteration and that's correct. The filenames are all correct.
It just seems to give up after a certain number of images, so my thought is that maybe there's a maximum number? I have over 50 frames that I want to stitch together.
The code snippet I'm working on:
delay_time = 0;
% for each frequency, read in the iso-contour and stitch to the plots
% together to make a gif
for counter_frequency = freq_min:freq_inc:freq_max
im_in = imread(['2D FFT, ' num2str(counter_frequency, '%3.2f') ' GHz.png'], 'png');
[imind,cm] = rgb2ind(im_in,256);
disp([num2str(counter_frequency)]);
if counter_frequency == freq_min
imwrite(imind,cm,[directory.plot.iso_plots '\Iso-frequency Animation.gif'],'gif','DelayTime',delay_time,'LoopCount',inf);
else
imwrite(imind,cm,[directory.plot.iso_plots '\Iso-frequency Animation.gif'],'gif','DelayTime',delay_time,'WriteMode','append');
end;
end;

Solved it! There was nothing wrong with my code after all - it was the program I was using to view the gif! Internet explorer is a bad idea guys. Always. Can't believe I forgot that! Found out the computer I was using for the coding had Chrome, opened it in Chrome out of curiosity - and it was fine.
Damn you, IE!

Related

Images turning green-blackish when passing them to dataloaders

I'm working with fastai, trying to pass some images to a dataloader. The original images are kind of pinkish, but after passing them they appear mostly as green-black (see image in link below):
Original pinkish image (up) and example images (down) after passing them to dataloader, and the code.
The code I've used for the datablock and to show the images is:
example = DataBlock(
blocks=(ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=GrandparentSplitter(),
get_y=parent_label,
item_tfms=Resize(128)) #already tried it without item_tfms just in case, still black-green
dls = example.dataloaders(path)
dls.show_batch(nrows=1, ncols=3)
I tried with .tif and .jpeg images, and both show the same problem. The only thing that comes to my mind is that somewhat somewhere is not reading correctly the color format (RGB according to my original files), or maybe transforming it; but I'm not able to figure it out.
Just in case it's important, I'm working in a Jupyter notebook with a MackBook Air M1.
Thanks!
Irene

Matlab create image from array and save without displaying

Apologies if this is a dupe, I've been searching for over an hour but the search terms are all really broad and I just keep getting the same results. Also I'm fairly new to matlab so apologies for any misunderstandings.
Anywho, I have a matlab program which needs to frequently save an image generated from a matrix, but I just can't figure out how to do that without displaying it first. Basically I'm caught in between two functions, image and imwrite, both only do half of what I want.
image is able to take my matrix and create the desired output, but it just displays it to a figure window
imwrite is able to save an image to a file without displaying it, but the image is completely wrong and I can't find any parameters that would fix it.
Other questions I've seen deal with using imread and managing figures and stuff, but I'm just doing (for example)
matrix = rand(20);
colormap(winter);
image(matrix, 'CDataMapping', 'scaled');
or
matrix = rand(20);
imwrite(matrix, winter(256), 'filename.png');
Is there some way to call the image function such that it doesn't display a figure window and then gets saved to a file? Something analogous to calling imshow and then savefig in matplotlib.
Just do this:
matrix = rand(20);
f = figure('visible', 'off');
colormap(winter);
image(matrix, 'CDataMapping', 'scaled');
print(f, '-dpng', 'filename.png');

MATLAB: overwriting images using print function

I'm using the print function in MATLAB to write images of plots, something like that
print(figure(1),'-dpng','-r300',filename);
But apparently the images are not overwritten, and the original images stay. I was using saveas before, which seems to overwrite the images, but print gives me more output options. Any ideas?
UPDATE: I ended up deleting the files before the printing with a different function.
You can use this:
im = frame2im(getframe(gcf,rec)); %Grabs image of plot as an image
imsave(im, filename); %save image
That syntax may not be 100%, its a while since I've used it.
Also be aware that this isn't perfect - I remember having issues with it grabbing a grey border around the edge of the plot. Also, I think the image may be based on a matlab screenshot.... just something to be aware of
Saving figures in matlab is rather troublesome, especially if the saved image should look like the original figure.
For myself i found the solution in using export_fig.
It's one of the most downloaded fileexchange files - maybe you should give it a try:
http://www.mathworks.de/matlabcentral/fileexchange/23629-export-fig
A small introduction to export_fig can be found at:
https://github.com/ojwoodford/export_fig/blob/master/README.md

MATLAB newbie: error using "saveas" to save a plot as a pdf file

I am a Mac (10.6.8) user. I have written MATLAB code for plotting calculation results and then saving the plots as pdfs. I use "saveas" (see example below).
I get this error:
??? Error using ==> print at 325
Problem converting PostScript. System returned error: -1.Failed to convert to output format; Ghostscript status: -100.**** Unable to open the initial device, quitting.
Error in ==> saveas at 155
print( h, name, ['-d' dev{i}] )
Error in ==> Results_processor at 1219
saveas(gcf,saveFigTo1, 'pdf')
Here is the relevant piece of code:
calculationResultsPath = '/Me/Projects/ThisProject';
calculationResultsDirectory = strcat( calculationResultsPath,'MATLABProcessedResults' );
mkdir( calculationResultsDirectory );
% ...Code for importing results to be plotted from external files (works fine)...
% ...Code for plotting (works fine)... I get the figures I want.
% The problem is:
saveFigTo1 = strcat(resultsDirectory,'/majorsMgO.pdf')
saveas(gcf,saveFigTo1, 'pdf')
hold off
pause
clf;
Some further information... This worked fine last week when I first wrote it! Since then, I think I updated to Mac OS 10.6.8 from 10.6.7, but nothing else has changed in my code or in the version of Matlab I use (R2009a) (unless I have a very bad memory!).
Also, I came across some older suggestions on similar questions to use "print." I tried using:
print(gcf,'filename'). I did get a pdf, but it would not open in any pdf viewing programme. I assume (but don't know for sure) that this could be related to the fact that I use a Mac. I have noticed that there are a few things (especially related to external file manipulation) that don't run on Mac.
If anyone could help, I would be very grateful.
Update:
I found a GhostScript for Mac and installed it as Chris suggested. Unfortunately, that didn't work. I read on a forum that many Mac users are having problems with MATLAB plots at present, possibly related to java. There was an operating system update (to OS X 10.6.8) last week and that is when the problems began. My code worked before then.
I still have not found a solution to this and I don't think the MATLAB people have either, so if anyone has suggestions about how to save plots WITHOUT using saveas, I would love to hear them. The "print" command does not work for me either--it produces PDFs that I can't open.
I think the problem here is GhostScript dying and not so much Matlab. A Google for that GS error turns up many pages such as this. Is this at all applicable? If you use GS outside of Matlab does it work?
As an aside, you might take a look at this FEX submission export_fig. It has treated me well. Worst case you could output to png and convert to PDF later.
One recommendation I can make is to use a different format that OS X understands and simply convert the result to pdf with a system call
See if the following works:
% Load a test image
im = imread('cameraman.tif');
imshow(im); % display the image
saveas(gcf,'test.tif','tif');
% convert to pdf using a syscall to cupsfilter
!cupsfilter test.tif > test.pdf 2> /dev/null
% open the file with your default pdf viewer
!open test.pdf
If the above is not working, yet another approach is to get the bitmap from the figure window and write it using imwrite. Note, this method doesn't benefit from the nice font scaling features of the saveas and print. This approach assumes the im variable above still exists.
imagesc(im); colormap gray;
% Set the border color to white
set(h,'Color',[1 1 1]);
% Get the image in the figure
frame = getframe(gcf);
imout = frame.cdata;
% on OS X, the stretch window image
% appears in the bottom right corner
% of the image. Remove it.
imout = imout(10:end-9,10:end-9,:);
% Write the image out to a lossless tif
imwrite(imout,'test.tif','tif','Compression','none')
You could then convert the tifs to pdf files as above. The quality of the figure will depend on the figure size. In most cases, I wouldn't use this second approach as saveas handles the fonts nicely. Using getframe is meant only as a workaround to the true problem with saveas.

How to easily crop the same image multiple times

I have a set of really big images out of which I need to crop little snippets. These snippets are all exactly the same size but don't follow a strict pattern so I can't do this programatically.
Ideally I would like to open up one of the big files and be able to point and click on say, the top left corner of a snippet and have that automatically be saved to disk without even having to enter a file name, and then continue on with the rest. (Of course this would be the ideal way which I know is probably way off the real possible way!).
I started doing this in Photoshop CS4 but cropping a snippet, saving, undoing (to get to the full image), and starting over again takes way too long.
Maybe someone has a better way to do this in photoshop or in some other software.
Thanks for reading!
Instead of cropping and undoing, you could:
make (or resize) a selection
copy the selection to a new image
save the image
close the image
You might need to split it into two actions, I don't know enough about programming Photoshop.
Thank you everyone for your input.
I ended up doing this with a suggestion a colleague of mine came up with. It consisted of creating a Photoshop "slice" over the first region I wanted to crop and then cloning that region over the rest of the other sections. After that, using Save For Web (and ofter hitting Continue when PS complained about how that image was way beyond Save For Web's capabilities) I could save all images at once.
This was the fastest and easiest method I could find. Until then I was going with Mark Ransom's method.

Resources