1

How does one change the bits per pixel of an image loaded into MATLAB? I use the file dialog and the imread functions to load the image into a matrix. i just need to change that image's bits per pixel. Giving the user that ability to choose anywhere from 1 bit to 8 bits. I know how to give the users the ability to choose one I just don't know who to change it. How does one change that? (By the way I'm in MATLAB R2012a)

Umdoobby
  • 105
  • 1
  • 5
  • 11
  • You should probably be a bit more specific about what result you want. Clearly a 1 bit image would be two colours, black and white, is that what you want? Also, the smallest element size is a single byte, so do you intend to pack the values or are you just restricting the range of values each pixel is allowed to take? – devrobf Apr 25 '13 at 19:17
  • Also, is there any chance you mean "byte" not "bit"? That would make more sense... – devrobf Apr 25 '13 at 19:21
  • no I meant bit, I know a 1 bit image would only be two colors – Umdoobby Apr 25 '13 at 19:23
  • and I guess I would just be limiting the range of values. But if I were to put just a solid limit on the values I would not be able to affect all of the elements in the matrix equally only the ones outside the range. How would I affect all of the elements equally? – Umdoobby Apr 25 '13 at 19:26
  • or would i want to affect all of the pixels equally? I was just told to change the bits per pixel of an image giving the user the ability to choose the number of bits – Umdoobby Apr 25 '13 at 19:33
  • I can't tell you what you want I'm afraid! I'll post an answer which explains how to scale the values of the image so that they are in the range allowed by a certain pixel depth. See if that is what you wanted. – devrobf Apr 25 '13 at 19:35

2 Answers2

0

This documentation page contains lots of information about what you want to do: Reducing the Number of Colors in an Image.

A simple example is the following (pretty much taken straight from that page), which will dither the image and produce a colour map (slightly different to the OP's answer - not sure which one you want to do):

>> RGB = imread('peppers.png');
>> [x,map] = rgb2ind(RGB, 2); % Reduce to a 2-colour image
>> imagesc(x)
>> colormap(map)

You should choose the number of colours based on the maximum number that however many bits can hold.

wakjah
  • 4,541
  • 1
  • 18
  • 23
0

The way I understand it, you want to do something like this:

imdata = rgb2gray(imread('ngc6543a.jpg') );  % Assuming that we have a grayscale uint8 image
figure('name', 'Before');
imagesc(imdata);
colormap('gray');

numberOfBits = input('Enter number of bits:\n');
maxValue = 2^numberOfBits - 1;

newImage = imdata * (maxValue / 256);
figure('name', 'After');
imagesc(newImage);
colormap('gray');

The image ngc6543a.jpg is a sample image, so you can run this code immediately as it is.

devrobf
  • 6,973
  • 2
  • 32
  • 46