【问题标题】:reading from bmp and writing to another bmp file, bytearray index error从 bmp 读取并写入另一个 bmp 文件,字节数组索引错误
【发布时间】:2013-11-28 22:13:54
【问题描述】:
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] 的字节数组吗?

【问题讨论】:

    标签: arrays python-3.x bitmap


    【解决方案1】:
    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 循环中移动了变量赋值并解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2014-05-22
      相关资源
      最近更新 更多