Powisss
Powisss

Reputation: 1142

matlab imwrite new image instead of overriding it

I have function that checks for bottle cap. If there is no cap detected, it writes it as an image into folder. My problem is that if I pass different image, the old one get overridden with new one, is there a way to make new image instead of overwriting old one such as nocap0,jpg, then new one nocap1.jpg etc?

Code:

function [  ] = CHECK_FOR_CAP( image )

%crop loaction of cap
imageCROP = imcrop(image,[130 0 100 50]);
%turn to BW
imageBW=im2bw(imageCROP);
%count black pixels
answer = sum(sum(imageBW==0));
%if <250 black, save it to folder NOCAP
if answer<250
    imwrite(image, 'TESTINGFOLDERS/NOCAP/nocap.jpg', 'jpg');
    disp('NO CAP DETECTED');
end

UPDATE

I changed the code a bit now. Everytime I give a different image it now writes new one, BUT it overwrites the previous one aswell like so: https://i.sstatic.net/0x4AI.jpg

My new code:

function [  ] = CHECK_FOR_CAP( image )

folder = 'TESTINGFOLDERS/NOCAP';
filePattern = fullfile(folder, '/*.*');
ImageFiles = dir(filePattern);
%crop loaction of cap
imageCROP = imcrop(image,[130 0 100 50]);
%turn to BW
imageBW=im2bw(imageCROP);
%count black pixels
answer = sum(sum(imageBW==0));
%if <250 black, save it to folder NOCAP
if answer<250
     a = length(ImageFiles)-1;
    for j = 1:a
        baseFileName = [num2str(j),'.jpg'];
        filename = fullfile(folder,baseFileName);
        if exist(filename,'file')
            imwrite(image,filename);
        end
        imwrite(image, fullfile(filename));
    end
    disp('NO CAP DETECTED');
end

Upvotes: 1

Views: 282

Answers (1)

Florian
Florian

Reputation: 1824

You write

for j = 1:a
    baseFileName = [num2str(j),'.jpg'];
    filename = fullfile(folder,baseFileName);
    if exist(filename,'file')
        imwrite(image,filename);
    end
    imwrite(image, fullfile(filename));
end

This means that whenever you find a file, you overwrite it. Then you overwrite it again. You do this for as many files as exist (a comes from some dir you do on your folder). What you want is the opposite: find one that does not exist. Something like this:

j = 0;
while true
    j = j + 1;
    baseFileName = [num2str(j),'.jpg'];
    filename = fullfile(folder,baseFileName);
    if ~exist(filename,'file')
        break
    end
end
imwrite(image, fullfile(filename));

This could be further shortened (e.g., by looping while exist(...)) but it conveys the idea...

Upvotes: 2

Related Questions