pbm-file created with Python only works when copy&pasted in new text-file

524 Views Asked by At

When I create a random image in .pbm-format (code below) and output the result in a .pbm-file, the file appears to be corrupt (cannot be opened e.g. with GIMP). However, if I open the file with a text editor (e.g. Notepad) and copy the content over to a new text file, that was manually created, it works fine.

I also tried outputting the image as .txt and manually changing it to .pbm, which did not work either without manually creating a new text file and copy&pasting the content. I also noticed that the text file created by Python is bigger in size (about double) compared to the manually created one with the same content.

Do you guys have any idea, why and how the .txt-file created in python differs from a manually created one with the same content?

Thanks a lot!

.pbm-file created with the following command in windows command line:

python random_image 20 10 > image.pbm

Code used:

import random
import sys

width = int(sys.argv[1]) #in pixel
height = int(sys.argv[2]) #in pixel

def print_image(width, height):

    image=[[" " for r in range(height)] for c in range(width)]

    print("P1 {} {}".format(width, height))

    for r in range(height):
        for c in range(width):
            image[c][r]=random.getrandbits(1)
            print (image [c][r], end='')
        print()

print_image(width, height) 
1

There are 1 best solutions below

2
aaldilai On

I've tested the code myself. I'm not sure how copy&paste worked for you (it didn't work for me), but it seems that your code produces something similar to this

P1 5 5
01101
01100
11010
01110
11000

But the pbm format expects spaces between the bits, so for the picture to be presented correctly, you have to produce something like

P1 5 5
0 0 1 1 1 
1 0 0 1 0 
1 1 0 1 0 
1 1 0 0 1 
1 1 1 1 1 

To get this result, just change the print statements of the bits to include a space at the end

print (image [c][r], end=' ') # notice the space