4

I have a jpg picture which is black and white and I would like to convert black part to white and white to black( black pixel to white and vise versa ) in MATLAB and save it as jpg file again. I have tried this code but it just give me a black line in the white page.

 im=imread('Export0000009111.jpg');
 binstring = dec2bin(im, 8);

 binImage = ~binstring;
 binImage = 1-binImage;
 binImage = (binImage == 0);
 imwrite(binImage,'ss1.png');

Does anyone has any proper solution for that?

Thanks in advance!

Divakar
  • 218,885
  • 19
  • 262
  • 358
Sam
  • 457
  • 1
  • 7
  • 15

3 Answers3

5

Code -

PATHNAME = 'Random.jpg'; %// Original image file
PATHNAME1 = 'RandomModified.jpg'; %// Modified image file

imwrite(uint8(255 - imread(PATHNAME)),PATHNAME1)
figure, imshow(imread(PATHNAME1))

When you read images, normally they come in 2D or 3D matrices with values in between 0 and 255, with 0 being black and 255 being white. So, we only need to subtract every pixel value from 255. This will do your job, will create negative images for gray images and for color image would be give a sense of "colored-negative" if I could invent a term like that.

Divakar
  • 218,885
  • 19
  • 262
  • 358
  • @ Divakar, what does PATHNAME1 = 'Red1.jpg';, I have just one picture which is black and white?!! – Sam Mar 10 '14 at 13:55
  • PATHNAME would be 'Export0000009111.jpg' and PATHNAME1 would be 'ss1.png'. Edit the code accordingly. – Divakar Mar 10 '14 at 13:56
3

To add to the other answer, if you want to perform binary operations on a black and white image, you need to convert it to a binary image first. So if you do:

im=imread('Export0000009111.jpg');
BW = im2bw(im,graythresh(im));

You can then use the approach you tried:

binImage = ~BW;
binImage = 1-BW;
binImage = (BW == 0);
imwrite(binImage,'ss1.png');
Cape Code
  • 3,584
  • 3
  • 24
  • 45
2

I have tried to make it more clear with description and images.

% read the input image
im = imread('rice.png');

% now convert the image to binary
bin_im = im2bw(im,graythresh(im));

% take complement of binary image
bin_im = imcomplement(bin_im);

% store the image in .jpg format
imwrite(bin_im,'ss1.png');

here are the outputs

           input image                  output image

input image output image

Ritesh
  • 256
  • 2
  • 13