0

I am trying to understand why I am not getting expected result from the following lines of code:

pix=np.asarray(Image.open(File))) #I am reading a pbm file into memory
img = Image.fromarray((pix), '1') #rewriting 
img.save("test1.pbm")

newpix=~pix #inverting the image
img = Image.fromarray((newpix), '1')
img.save("test2.pbm")

original image and test1.pbm(image 1) is same, but test2.pbm (image 2) isn't what I am expecting (the foreground pixels become background ones and vice versa). I am attaching the images here (converted to jpeg). What am I doing wrong?

Another issue is that for most of the foreground pixels in test1.pbm, the value is False. But that is not reflected in the saved image.

I converted both of these images from this original image http://www.mathgoodies.com/lessons/graphs/images/line_example1.jpg using Imagemagick. test1.jpg

test2.jpg

rivu
  • 2,004
  • 2
  • 29
  • 45

1 Answers1

0

I don't recognise which language you are using, but your original image, when converted with ImageMagick like this:

convert cdLTY.jpg -negate out.jpg

looks like this:

enter image description here

So I deduce the problem is in your inversion. I don't know what

newpix=~pix

does (probably complelementing it or inverting all the bits?) but I think you need to subtract each pixel from 255 to invert your image, so if a pixel is 10 in the original image, it needs to be 255-10 or 245 in the new image.

Explanation

Pixels are normally encoded with 0=black and 255=white. So, if your pixel was originally black (0) when you do new pixel = 255 - original value, it will become 255-0, or 255 meaning it is now white. Likewise, if a pixel starts off white (255), when you do 255-255 you get 0 which is now black.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • i'm using python and the original image, when read, returns a boolean array. – rivu Sep 30 '14 at 15:42
  • What happens if you multiply the elements of `img` by 255 before you do `img.save("test1.pbm")`? And if you then calculate each element of `newpix` as `255-oldvalue`? – Mark Setchell Sep 30 '14 at 16:13