Re saving images with Transparent background and uncompressed

조회 수: 9 (최근 30일)
Hi,
My query is very simple. I am basically renaming images *.JPG files. However, renamed and saved files are showing background and are compressed.
How can I keep background transparent and can I save them as uncompressed.
p=dir('Data\*.jpg'); %input files
filenames = {p.name};
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[~, basename, ~] = fileparts(thisfile);
newname = sprintf("%d.jpg", K);
out_path = 'Data'; % Give path here
fullFileName = fullfile(out_path, newname);
data = imread(thisfile);
imwrite(data, fullFileName);
end

채택된 답변

Florian Bidaud
Florian Bidaud 2024년 3월 8일
편집: Florian Bidaud 2024년 3월 8일
If you just want to rename them, you don't need to load and save, you can just use copyfile.
If you want to do stuff after loading the image and then save it without the background, you need to load with BackgroundColor = 'none'. But here I'm surprised as you use a jpg file, which cannot contains transparent pixels. Could you show an example of input and output of your image ?
data = imread(thisfile,BackgroundColor='none');
  댓글 수: 2
DGM
DGM 2024년 3월 8일
편집: DGM 2024년 3월 8일
This is correct. There isn't any transparency information, at least not in a base JPG. JPEG2000 does support transparency, but imread() can't read it, and imwrite() can't write it. So either you have no transparency, or you do, and there's nothing you can do with it in MATLAB.
If you're editing JPGs from another source (e.g. a camera or photoshop), then avoid transcoding through MATLAB at all costs. As a general rule, avoid ever writing to JPG if at all possible. MATLAB cannot write anything but a 4:2:0 downsampled JPG (default is 75%). As lossy JPGs go, that's a trash-quality JPG.
EDIT: imwrite() can write a 4:4:4 JPG or JP2, but only if the 'lossless' option is selected. At that point, we have to question whether there's any point in using JPG/JP2 anymore, since a lot of things won't read a lossless JPG/JP2, and you're probably not getting any more compression than you would just using a widely-supported PNG.
Abdul Hannan Qureshi
Abdul Hannan Qureshi 2024년 3월 9일
편집: Abdul Hannan Qureshi 2024년 3월 9일
Thanks @Florian Bidaud and @DGM. I really misunderstood the data, after your explanation, I rechecked it again and my interpretation was wrong about *.jpg (there was no change in background, it was a glitch on my side). I have changed the output to *.png now, and compression issue is very much resolved.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by