0

I have a test.pbm file in ASCII mode containing the code as follows:

P1
# Comment
9 9
000000000
011000000
011000000
011000000
011000000
011000010
011111110
011111110
000000000   

I want to make a new file "newFile.pbm" which will contain space between every two pixels. Like as follows:

P1
# Comment
9 9
0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 1 0
0 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 

I have tried to open the file "test.pbm" with the following code to do the work, but I have faced many problems, firstly, it shows 'IOError: cannot identify image file' when opening .pbm, secondly, can not make the space between every two pixels. Actually I am new in Python. My os Linux Mint 17.3 cinamon 32bit and Python2.7.6. Plese help. The code I have tried given below:

fo=open("test.pbm",'r')  
columnSize, rowSize=fo.size
x=fo.readlines()
fn = open("newfile.pbm","w") 
for i in range(columnSize):
     for j in range(rowSize):
      fn.write(x[i][j])
fn.close()
Primo
  • 19
  • 5

1 Answers1

0

You could do something like this:

with open("test.pbm", 'r') as f:
    image = f.readlines()

with open("newfile.pbm", "w") as f:
    f.writelines(image[:3])   # rewrite the header with no change
    for line in image[3:]:    # expand the remaining lines
        f.write(' '.join(line))
sal
  • 3,515
  • 1
  • 10
  • 21
  • Thank you for your answer. It works fine. If I want to change every pixels in the new file as my choice, How can I do that? – Primo Nov 30 '16 at 17:41
  • I don't understand the question. – sal Nov 30 '16 at 19:18
  • How can I read every pixels of the new pbm file "newfile.pbm"? – Primo Dec 01 '16 at 01:13
  • After you read the file in with `f.readlines()`, you are returned a list of lines, which will be a string like '0 1 1 0 0 0 0 1 0'. You can then just split the line (`pixels = line.split()`), and this returns a list (`['0', '1', '1', '0', '0', '0', '0', '1', '0']`), where each element can be addressed by index, like `pixels[0]`, `pixels[2]` and so on. Note that these will still be `str` so you might have to convert them to `int`. – sal Dec 01 '16 at 02:28
  • Can you tell me please how to see image size of this pbm file. I have used "image.size" but it shows error: print image.size AttributeError: 'list' object has no attribute 'size'. @Sal – Primo Dec 01 '16 at 03:58
  • Right. We are treating the image as just an ASCII file, thus there is no `size` property, nor an `image` for that matter. So, unless you find and use a library that supports `pbm`, you will have to find the size of the image from the spec itself (http://netpbm.sourceforge.net/doc/pbm.html) which tells that the size of the image is specified in the header (9 9 in your case) which means 9 rows by 9 columns. – sal Dec 01 '16 at 05:53