2013-11-28 50 views
0
BMP_LOCATION = 10 
NO_BYTES = 3  
def image_gray(in_file, out_file): 
     in_file.seek(BMP_LOCATION) 
     data_start = int.from_bytes(in_file.read(4), "little") 
     in_file.seek(0) 
     header = in_file.read(data_start) 
     out_file.write(header) 
     pixel = bytearray(in_file.read(NO_BYTES)) 
     pixel1 = pixel[0] 
     pixel2 = pixel[1] 
     pixel3 = pixel[2] 
     while len(pixel) > 0: 
      grays = (pixel1*0.33) + (pixel2*0.6) + (pixel3*0.06) 
      grays_int = int(grays) 
      gray_pixel = bytearray([grays_int, grays_int, grays_int]) 
      out_file.write(gray_pixel) 
      pixel = bytearray(in_file.read(NO_BYTES)) 
      pixel1 = pixel[0] # these last 3 index lines are the problem 
      pixel2 = pixel[1] 
      pixel3 = pixel[2] 
     return 

我試圖把一個BMP圖像,並使其從原來的讀取顏色和寫出轉換的灰度到一個新的圖像灰度。但是,當我嘗試運行該程序時,出現索引錯誤,指出bytearray的索引超出範圍。爲什麼是這樣?不應該在while循環中每次新讀取仍然帶回一個索引爲[0,1,2]的字節數組?從BMP讀取和寫入到另一個bmp文件,字節數組的索引錯誤

回答

0
BMP_LOCATION = 10 
NO_BYTES = 3 
def image_gray(in_file, out_file): 
    in_file.seek(BMP_LOCATION) 
    data_start = int.from_bytes(in_file.read(4), "little") 
    in_file.seek(0) 
    header = in_file.read(data_start) 
    out_file.write(header) 
    pixel = bytearray(in_file.read(NO_BYTES)) 
    while len(pixel) > 0: 
     pixel1 = pixel[0] # was doing this twice previously 
     pixel2 = pixel[1] 
     pixel3 = pixel[2] 
     grays = (pixel1*0.33) + (pixel2*0.6) + (pixel3*0.06) 
     grays_int = int(grays) 
     gray_pixel = bytearray([grays_int, grays_int, grays_int]) 
     out_file.write(gray_pixel) 
     pixel = bytearray(in_file.read(NO_BYTES)) 
    return 

在盯着代碼一段時間後,我意識到沒有理由在while循環之前和之內爲每個索引值賦值變量。我在while循環中移動了變量賦值並解決了我的問題。