Effacer les filtres
Effacer les filtres

Why binary images are not stored as logical when imwrite is used with .jpg file extension

3 vues (au cours des 30 derniers jours)
Deepak Panda
Deepak Panda le 23 Août 2016
Modifié(e) : DGM le 18 Mar 2022
clc;
clear all;
close all;
img = imread('cameraman.tif');
bimg = img>128;
imwrite(bimg,'img1.bmp');
imwrite(bimg,'img2.jpg');
imwrite(bimg,'img3.tiff');
imwrite(bimg,'img4.png');
img1 = imread('img1.bmp');
img2 = imread('img2.jpg');
img3 = imread('img3.tiff');
img4 = imread('img4.png');
img1, img3 and img4 are all logical except img2 which is stored in .jpg file extension. Why so?

Réponses (1)

DGM
DGM le 18 Mar 2022
Modifié(e) : DGM le 18 Mar 2022
From the documentation:
  • For grayscale images, the BitDepth value can be 8, 12, or 16. The default value is 8. For 16-bit images, the 'Mode' name-value pair argument must be 'lossless'.
  • For color images, the BitDepth value is the number of bits per plane, and can be 8 or 12. The default is 8 bits per plane.
As far as I know, the minimum bit depth supported by the format is 8.
That said, JPEG2000 supports 1-bit images. See the table here for all formats:
I suppose a crafty person could get creative and try to pack binary data into uint8, but the lossy compression would surely destroy the content. There wouldn't be much point to using JPG for such a scheme.
EDIT: To prove that last point:
A = imread('peppers.png');
sz = size(A);
% binarize all three channels
map = [0 0 0; 1 1 1; hsv(6)];
A = ind2rgb(rgb2ind(A,map),map);
imshow(A)
% create packed image
charmap = {'0' '1'};
Achar = reshape(vertcat(charmap{A+1}),[],8);
Adec = uint8(reshape(bin2dec(Achar),sz(1),[],3));
%imshow(Adec)
% transport the image
fname = 'test.jpg';
imwrite(Adec,fname,'quality',100); % highest quality!
Bdec = imread(fname);
% unpack image
Bchar = dec2bin(Bdec(:));
B = double(reshape(Bchar == '1',sz(1),[],3));
imshow(B) % the result is still garbage!
Note that even with 100% quality, imwrite() still uses 4:2:0 chroma subsampling, so you shouldn't be using JPG for anything anyway. While the above example packs data into a 3-ch image, packing into a single-channel image will reduce the damage by avoiding the chroma subsampling. Still, the compression is lossy and damage will occur.
You're free to try the above code with a lossless format and see that it does in fact work.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by