2

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) 
Patrick
  • 21
  • 3

1 Answers1

0

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
aaldilai
  • 271
  • 1
  • 6
  • Thanks, aaldilai, Even with the spaces, the issue remains the same for me. If the file is created by Python, GIMP throws an "invalid file" error. Copy&paste without the spaces definitely worked for me. I made sure to copy everything to the manually created pbm-file (including all white space) to make sure to have exactly the same content. I feel like the fact, that the files created by Python are bigger is a good indicator. Why would the file size be different, if the content is exactly the same? – Patrick Jul 30 '18 at 02:06
  • hmm.. I might not know the solution, but I can recommend a way to debug. Take the contents of the generated pbm file and print it as ascii `[ord(c) for c in file_str], compare that to the copied string. You might find invisible characters that you didn't expect, and that might be a lead. – aaldilai Jul 30 '18 at 02:27