def Read_raw(filename,w,h,m):
#初始化image
image=[]
for i in range(m*h):
image.append([])
for j in range(w):
image[i].append(255)
#读取raw
with open(filename,'rb') as f:
data=f.read()
#写入raw
for i in range(m*h):
for j in range(w):
image[i][j]=data[i*w+j]
print('读取文件{0}成功'.format(filename))
return image
def Write_raw(filename,image):
#将数组image转为bytes
bt=bytearray()
for i in range(len(image)):
for j in range(len(image[i])):
bt.append(image[i][j])
#写入raw
with open(filename,'wb') as f:
f.write(bt)
f.close()
print('写入文件{0}成功'.format(filename))
def change(image):
red=[]
green=[]
blue=[]
#遍历得像素点的最大值
L=0
for i in range(len(image)):
for j in range(len(image[i])):
if image[i][j]>L:
L=image[i][j]
print('得到像素点最大值为{0}'.format(L))
print('计算彩色图像素值中---')
for i in range(len(image)):
red.append([])
green.append([])
blue.append([])
for j in range(len(image[i])):
if image[i][j]<L/4:
red[i].append(0)
blue[i].append(L)
green[i].append(4*image[i][j])
elif image[i][j]>=L/4 and image[i][j]<L/2:
red[i].append(0)
blue[i].append(2*L-4*image[i][j])
green[i].append(L)
elif image[i][j]>=L/2 and image[i][j]<3*L/4:
red[i].append(4*image[i][j]-2*L)
blue[i].append(0)
green[i].append(L)
elif image[i][j]>=3*L/4 and image[i][j]<=L:
red[i].append(L)
blue[i].append(0)
green[i].append(4*L-4*image[i][j])
else:
print('error')
print('计算完成。')
#非隔行存储
colour=[]
for i in range(len(red)):
colour.append(red[i])
for i in range(len(green)):
colour.append(green[i])
for i in range(len(blue)):
colour.append(blue[i])
return colour
image=Read_raw('test2.raw',2823,2320,1)
colour=change(image)
Write_raw('test2_colour.raw',colour)