2016-12-01 89 views
1

讓我們考慮的例子:如何在ASCII模式下讀取pbm文件的大小?

的PBM文件「imFile.pbm」中包含的像素如下:

P1 
# Comment 
9 6 
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 0 0 0 0 0 0 0 0  

如何確定圖像的寬度和高度。我已經使用了下面的代碼,但失敗了。

with open("imFile.pbm", 'rb') as f: 
    image = f.size 
    print image 
    f.close() 

當我編譯它在我的ubuntu14.04操作系統,它顯示錯誤。任何建議將不勝感激。先謝謝你。

+0

的寬度和高度,就在那裏的文件中,第一行中的第一個之後,跳過評論。這不是'.size'的用途;你需要閱讀和解析文件。 – Amadan

+0

@ Amadan--我該怎麼做?你能解釋我的話嗎? –

回答

0

寬度和高度就在文件中,在第一行之後的第一行中,跳過註釋。這不是什麼大小。你需要閱讀和解析文件。

with open("imFile.pbm", 'r') as f: 
    lines = f.readlines() 
lines.pop(0)      # skip header 
line = lines.pop(0)    # get next line 
while line.startswith("#"):  # repeat till that line is not a comment 
    line = lines.pop(0) 
width, height= line.split()  # split the first non-comment lin 
print("%s x %s" % (width, height)) # => 9 x 6