필터 지우기
필터 지우기

How to save output images after preprocessing into new folder sequentially without overwriting?

조회 수: 1 (최근 30일)
I am have to convert RGB images into gray scale, as there are hundreds of images in that folder. I want to processess all and save the resultant gray scale images into different folder. Can I get code for this?

채택된 답변

KSSV
KSSV 2021년 7월 28일
infolder = '' % give the path of the folder where your RGB images are present
outfolder = '' % give the path of the folder where you want to save gray images
imgFiles = dir([infolder,filesep,'\*.png']) ; % give extension of your images
N = length(imgFiles) ; % total images in the foder
for i = 1:N
thisFile = [infolder,filesep,imgFiles(i).name] ; % each image file
[filepath,name,ext] = fileparts(thisFile) ; % get name of the image file and extension
outFile = [outfolder,filesep,[name,ext]] ; % write gray image file on this name here
I = rgb2gray(imread(thisFile)) ; % reac and conver RGB image into gray
imwrite(I,outFile) ; % write the gray image in the said folder on the name
end
  댓글 수: 7
Stephen23
Stephen23 2021년 7월 28일
편집: Stephen23 2021년 7월 28일
Assuming that the first two filenames are '.' and '..' is buggy, anti-pattern, and not recommended.
@Nikhat Ali: Do NOT follow any poor advice advising to remove the first two filenames. Your original approach of specifying the file-extension is a much more robust approach. Or you could remove any folders using the ISDIR field:
S = dir(..);
S([S.isdir]) = [];
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
Unfortunately poor advice keeps getting repeated and copied by beginners.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Convert Image Type에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by