I'm trying to save my data 'Images' after some treatment by using imwrite but the problem is that imwrite does not work for a sequence. I've read some solutions and tried them but they don't work. This is how I wrote my code, for example:
%read the sequence
for i=1:k
%treatment
Id{k} = waverec2(t_C,L,'sym8');
fileName = sprintf('C:\\Users\\swings\\Desktop\\data\\imagesPourAlgo\\images.tiff\\%02d',k);
imwrite ( Id, 'fileName', 'tif');
end
Knowing that I want to save 'write' each image separately for doing another process on them.
Why don't you try something like this:
for i = 1:10
I = waverec2(t_C,L,'sym8'); % or whatever you have
filename = ['c:\some\directory\file_number_' num2str(i) '.tif'];
imwrite(I,filename);
end
Personally,I prefer not to use 'sprintf' in such simple cases.
Your second input argument for imwrite is the char array fileName. Use the variable instead. The image is probably Id{k} and not Id:
imwrite ( Id{k}, fileName, 'tif');
Related
I have a set of images located in a folder and I'm trying to read these images and store their names in text file. Where the order of images is very important.
My code as follow:
imagefiles = dir('*jpg');
nfiles = length(imagefiles); % Number of files found
%*******************
for ii=1:nfiles
currentfilename = imagefiles(ii).name;
% write the name in txt file
end
The images stored in the folder in the following sequence : {1,2,3,4,100,110}.
The problem that Matlab read and write the sequence of images as { 1,100,110,2,3,4}. Which is not the correct order.
How can this be overcome?
I would suggest to use scanf to find the number of the file. For that you have to create a format spec which shows how your file name is built. If it is a number, followed by .jpg, that would be: '%d.jpg'.
You can call sscanf (scan string) on the name's of the files using cellfun:
imagefiles = dir('*jpg');
fileNo = cellfun(#(x)sscanf(x,'%d.jpg'),{imagefiles(:).name});
Then you sort fileNo, save the indexes of the sorted array and go through these indexes in the for-loop:
[~,ind] = sort(fileNo);
for ii=ind
currentfilename = imagefiles(ii).name;
% write the name in txt file
end
I want to copy all images in a file to another file with different names. But, images order changes during copy. For example, this order like that: B0. jpg,B1.jpg,..,B9.jpg,B10.jpg,B11.jpg..,B30.jpg. I want to change the name of B0.jpg to image1.jpg, B1.jpg to image2.jpg in a similar. But, it changes B0.jpg to B10.jpg and then B11.jpg instead of B1,B2,B3...Because of that images order changed. How can I fix this problem?
The problem is the SO orders the file names using ASCII sorting, as they're strings (it doesn't look to numbers differently). The string "10" is placed before the string "2", because "1" < "2".
Instead of relying on the order, you could do something like this:
imgs = dir('*.jpg');
for i = 1:numel(imgs)
% Change the 'B' to 'image'
newName = strrep(imgs(i).name, 'B', 'image');
% Copy the image
copyfile(imgs(i).name, ['c:\destination\' newName]);
end
I am trying to change a file by finding this string:
<aspect name=\"lineNumber\"><![CDATA[{CLONEINCR}]]>
and replacing {CLONEINCR} with an incrementing number. Here's what I have so far:
file = File.open('input3400.txt' , 'rb')
contents = file.read.lines.to_a
contents.each_index do |i|contents.join["<aspect name=\"lineNumber\"><![CDATA[{CLONEINCR}]]></aspect>"] = "<aspect name=\"lineNumber\"><![CDATA[#{i}]]></aspect>" end
file.close
But this seems to go on forever - do I have an infinite loop somewhere?
Note: my text file is 533,952 lines long.
You are repeatedly concatenating all the elements of contents, making a substitution, and throwing away the result. This is happening once for each line, so no wonder it is taking a long time.
The easiest solution would be to read the entire file into a single string and use gsub on that to modify the contents. In your example you are inserting the (zero-based) file line numbers into the CDATA. I suspect this is a mistake.
This code replaces all occurrences of <![CDATA[{CLONEINCR}]]> with <![CDATA[1]]>, <![CDATA[2]]> etc. with the number incrementing for each matching CDATA found. The modified file is sent to STDOUT. Hopefully that is what you need.
File.open('input3400.txt' , 'r') do |f|
i = 0
contents = f.read.gsub('<![CDATA[{CLONEINCR}]]>') { |m|
m.sub('{CLONEINCR}', (i += 1).to_s)
}
puts contents
end
If what you want is to replace CLONEINCR with the line number, which is what your above code looks like it's trying to do, then this will work. Otherwise see Borodin's answer.
output = File.readlines('input3400.txt').map.with_index do |line, i|
line.gsub "<aspect name=\"lineNumber\"><![CDATA[{CLONEINCR}]]></aspect>",
"<aspect name=\"lineNumber\"><![CDATA[#{i}]]></aspect>"
end
File.write('input3400.txt', output.join(''))
Also, you should be aware that when you read the lines into contents, you are creating a String distinct from the file. You can't operate on the file directly. Instead you have to create a new String that contains what you want and then overwrite the original file.
I have image files that I want to append a string to the name of the file, right before the extension.
Example: example.png would turn in to example-2x.png
So, I want to insert -2x right before the extension, would could be just about any image type (png, jpg, gif, etc).
If there's an easy way to do this with Ruby, great.
Rake has a nice string extension for manipulating paths:
require 'rake/pathmap'
"images/example.png".pathmap "%X-2x%x"
#=> "images/example-2x.png"
From pathmap's docs:
%X -- Everything but the file extension.
%x -- The file extension of the path. An empty string if there is no extension.
This seems to work
img[/(\.\w+)/] = "-2x#{$1}"
img1 = 'foo.png'
img1[/(\.\w+)/] = "-2x#{$1}"
img1 #=> "foo-2x.png"
img2 = 'foo.bar.jpg'
img2[/(\.\w+)/] = "-2x#{$1}"
img2 #=> "foo-2x.png.jpg"
Use basename and extname to extract the two parts you want:
http://www.ruby-doc.org/core-2.0/File.html#method-c-basename
http://www.ruby-doc.org/core-2.0/File.html#method-c-extname
def insert_before_last_dot(str, part)
idx = str.rindex('.')
return str if (idx.nil? || idx==0)
str.clone.tap { |x| x[idx] = part.to_s + '.' }
end
insert_before_last_dot('foo.jpg', '-2px') # => "foo-2px.jpg"
insert_before_last_dot('foo.bar.jpg', '-2px') # => "foo.bar-2px.jpg"
insert_before_last_dot('foo') # => "foo"
Here's what I ended up doing that seems to work pretty well across pretty much any file type.
image = 'example.png'
ext = File.extname(image)
image_2x = image.gsub(ext, "-2x"+ext)
I dont know ruby myself, but I would expect that there is some sort of string.lastIndexOf() like in java. So you basically just find the last dot, split the string around that, and then reconcatinate it with the -2x
If you're working in a Linux environment, the rename function should work.
rename {,\-2x,*}.png
In tcsh and bash shells this expands to rename .png \-2x.png *.png
> "example.png".gsub /\.[^\.]*$/, "-2x\\0"
=> "example-2x.png"
I am sure that all of the above answers are more proper than mine but i find it effective to use the replace function...
Dir | Rename-Item -NewName {$_.name -replace ".pdf"," - 2012.pdf"}
So you just take the file extension .png and replace it with -2x.png
this should work with any file extension as you are just replacing it with the same or even a different file extension and add whatever text you want before the file extension.
I am working in Matlab environment for a project, and I have to decode a RGB image received in xml from the database server, which is encoded in base64 format. I was successful in converting image to base64 and post it to the database by converting it into xml. I used the base64encode/decode to encode the image to base64 and I have attached the program below. The problem is when I use the base64decode function and try to reconvert the image from base64. It simply does not work.
This is my program for converting image to base64 and encode it in xml.
function image2xml(test_directory)
% Images in directory ---> byte array format in XML
% This function encodes all the images available in the test directory into
% byte array/base 64 format and saves them in xml with the following
% properties
% Packs the image(byte array) and its name as timestamp to xml
% Uses functions from the following source
% http://www.mathworks.de/matlabcentral/fileexchange/12907-xmliotools
% Following functions from the above source are to be added to path,while
% running this function
% xml_write.m
% xml_read.m
%% ========================================================================
files=dir(test_directory)
% delete('test_image_xml\*.xml');
% If not database_mat is included in the function arguments
for i = 1:size(files,1)
k=0;
if files(i).isdir()==0
%extracts name with which it savesa as xml
[~, name_to_save,~ ] = fileparts(files(i).name)
filename = fullfile([test_directory,'\',files(i).name])
fid = fopen(filename);
raw_data = uint8(fread(fid));% read image file as a raw binary
fclose(fid);
%Definition of xml tags
image_imagedetails = [];
% name of the file is assumed to be the timestamp
image_imagedetails.timestamp =name_to_save;
%imagescan.imagebyte64.ATTRIBUTE.EncodingMIMEType = 'base64';
image_imagedetails.imagebase64 = base64encode(raw_data);% perform base64 encoding of the binary data
%saves all the xml files into the predefined directory
mkdir('images_and_timestamp_xml');
filename = ['images_and_timestamp_xml\' name_to_save,'.xml' ];
post_data = xml_write(filename, image_imagedetails);
end
end
Finaly I use the following to reconvert the xml created with image in base64 format back to image, but unfortunately it does not work, and throws some strange characters, which I am not able to convert back into a image. I further have no clue as of how to convert the string back to image as well.
filename = '...\IMAG0386.xml';
tree = xml_read(filename);
image = tree.imagebase64;
K = base64decode(tree.imagebase64)) %test image retrieval --> only the string
And I tried out other option like using the Java code in matlab, but I do not know, how to use the code in matlab. There are many options in C#, Java, but I have no idea, as how to use them in matlab. Please help me in this regards.
I ran your code under Matlab R2012a and it seems to work as expected.
Maybe what is missing here is a few lines to get the image file back from the binary data encoded in base64. You just need to write the binary data to a file to get your image file back.
I am merely quoting the HTML help file from the Matlab FileExchange submission xmliotools that you are using in your code:
Read XML file with embedded binary data encoded as Base64 (using java
version)
tree = xml_read('test.xml', Pref); % read xml file
raw = base64decode(tree.MyImage.CONTENT, '', 'java'); % convert xml image to raw binary
fid = fopen('MyFootball.jpg', 'wb');
fwrite(fid, raw, 'uint8'); % dumb the raw binary to the hard disk
fclose(fid);
I = imread('MyFootball.jpg'); % read it as an image
imshow(I);
Simple Base64 Handling
Using the Apache library
base64 = org.apache.commons.codec.binary.Base64
Then you can call encode or decode.
base64.encode()
base64.decode()
It expects byte[], so you can get this in a couple of ways. Let's encode a string and then decode it.
hello = 'Hello, world!';
encoded = char(base64.encode(unicode2native(hello))).';
result = native2unicode(base64.decode(uint8(output)).');