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]的字节数组吗?
答案 0 :(得分: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循环中移动了变量赋值并解决了我的问题。