how to replace the name of image with a number?

hello, I have a dataset that contain 300 images. the name of image is :
464_img_2,464_img_3,464_img_4,464_img_5
.
.
.
1017_img_2,1017_img_3,1017_img_4,1017_img_5
I want to replace the beginning of image name in the order of 1 to 300 as shown:
1_img_2,1_img_3,1_img_4,1_img_5
.
.
.
300_img_2,300_img_3,300_img_4,300_img_5
please, help me, How can do it?

1 Comment

Is each line here one string, or multiple strings? Can you please upload your data for us to try out.

Sign in to comment.

 Accepted Answer

Stephen23
Stephen23 on 18 Jan 2016
Edited: Stephen23 on 18 Jan 2016
This converts the first digits into their relative indices, putting them into ascending order:
C = {'464_img_2','464_img_3','464_img_4','464_img_5','1017_img_2','1017_img_3','1017_img_4','1017_img_5'};
D = regexp(C,'\d+','match','once');
[~,~,X] = unique(str2double(D));
E = arrayfun(@num2str,X,'UniformOutput',false);
F = regexprep(C,strcat('^',D),E)
The input and output strings are:
>> C
C =
'464_img_2' '464_img_3' '464_img_4' '464_img_5' '1017_img_2' '1017_img_3' '1017_img_4' '1017_img_5'
>> F
F =
'1_img_2' '1_img_3' '1_img_4' '1_img_5' '2_img_2' '2_img_3' '2_img_4' '2_img_5'

7 Comments

this not work, the database contain 300 images
Can you please explain exactly what "this not work" means. Have you tried the code? What did it do that you did not expect?
Perhaps I misunderstood the nature of your data. Please upload the exact array of names that you need to be converted. Currently your question does not adequately explain the format of this data.
Your data is not in a dataset as you state in your question, but appears to be the structure returned by the function dir. You only need to run this line first:
C = {baseFileNames.name};
and the rest of my code exactly as before:
D = regexp(C,'\d+','match','once');
[~,~,X] = unique(str2double(D));
E = arrayfun(@num2str,X,'UniformOutput',false);
F = regexprep(C,strcat('^',D),E)
Sort Order
The only remaining question is the order: the filenames that you supplied are not in numeric order. If you want those filenames numbered according to number order then use my code as above. If you want the same order as dir returned (which is not specified in the documentation), then use the 'stable' option in unique:
[~,~,X] = unique(str2double(D),'stable');
I used a dataset that contain 1200 images but for simplycity,I upload the list of names because the dataset is very large. I tried to use this code, so good, these names are changed, but when I open the folder containing the dataset, the names are not changed. how can I save the result?
If you want to rename the file on disk, use movefile(oldfilename, newfilename).

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type 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!