Read in a general binary file (for example, but not exclusively a jpeg file), make a modification and write a new file out verbatim--no altered bytes.
5 次查看(过去 30 天)
显示 更早的评论
Someone has written a Python program that I would like to translate into MATLAB:
There are stereoscopic (3D) files that are just concatenated jpegs. There are two FF D8 byte pairs signifying the beginning of a jpeg. The software produces separate jpegs for each of the two concatenated jpegs.
My program reads in the file with
bytes=fileread(infilename);
It then finds the two occurrences of FF D8 (as 255 and 216):
beginBytes=strfind(bytes,char(255));
for i=1:length(beginBytes)
if bytes(beginBytes(i)+1)==char(216)
jpegCtr=jpegCtr+1;
offsets(jpegCtr)=beginBytes(i)
end
end
and tries to write out the first included jped:
fid=fopen('c:\stereophotomaker\childrens library_l.jpg','w');
% fprintf(fid,'%s',bytes(offsets(1):offsets(2))); % first tried way
%fwrite(fid,bytes(offsets(1):offsets(2)),'*char'); % second
fprintf(fid,'%s',bytes); %third
fclose('all');
but even when attempting a fraction of the original file, the newly created file is larger than the half file attempted, and the last trial produces a file larger than the whole original file, even though it's the same bytes.
Regardless of which method used, the resulting file is not recognized by Windows Media Player, though called a .jpg.
采纳的回答
Les Beckham
2023-7-28
fileread reads the file as text. You need to open the file and read it as binary bytes (uint8) and then process it that way.
Replace
bytes=fileread(infilename);
with
fp = fopen(infilename, 'r');
bytes = fread(fp, 'uint8')
and also replace your
beginBytes=strfind(bytes,char(255));
with
beginBytes = find(bytes == uint8(255));
and similarly for finding the 216 marker(s).
3 个评论
更多回答(1 个)
Image Analyst
2023-7-29
See the FAQ for how to read in a series of files.
After you read them in, create an output file name that has PNG as the extension and call imwrite. Then it will write out the new image with exactly the same values it has in MATLAB. At this point, you'll have the same pixel values regardless if you read in the JPG version of the file or the PNG version of the file. Whatever you're going to do with the image matrices after that does not care what format the original disk files were in, so you might as well just stick with the JPG files (unless you plan on modifying the image matrix out and resaving it).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!