class PPM(object):
def __init__(self, infile, outfile):
self.infile=infile
self.outfile=outfile
#Read in data of image
data= open(self.infile,"r")
datain=data.read()
splits=datain.split()
#Header info
self.type=splits[0]
self.columns=splits[1]
self.row=splits[2]
self.colour=splits[3]
self.pixels=splits[4:]
def greysscale():
for row in range(rows):
for column in range(columns):
r, g, b = image.getPixel(row, column)
brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
image.setPixel(row, column, color_rgb(brightness, brightness, brightness))
def flattenred():
for colour in range (0,len(self.pixels),3):
self.pixels [colour]=str[0]
return picture
def writetofile(self):
dataout= open(self.outfile,"w")
dataout.write(self.type +"\n" + self.columns + "\n" + self.row +"\n"+ self.colour +"\n"+ " ".join (self.pixels))
sample= PPM("cake.ppm", "Replica.ppm")
sample.writetofile()
我在编写名为grey_scale的函数时遇到了麻烦,该函数通过对一个像素(红色,绿色和蓝色)的所有三个色号取平均值,然后将其全部替换为该平均值,将图片转换为灰度图像。
因此,如果这三种颜色分别为25、75和250,则平均值将为116,所有三个数字将变为116。
我该怎么做?
最佳答案
rom_file= [0,3,1]
#Main Function which adds s dots and xs to the deck list(s) depending on the data input file
def main():
#Container for the output of the program, each nested list contains one row of the output
decks = [[], [], [], [], []]
#list that contains the number of empty rows for inputs 1-5(location of input given by [each - 1])
empty_rows = [4, 3, 2, 1, 0]
#Scan through each element of the list
for each in from_file:
#If the element 'each' is equal to 0, append a single dot to all 5 rows
if each == 0:
for i in range(5):
decks[i].append('.')
#If the input is in the range 1-5, define variables and the nested for loops
else:
#Maximum width of each pyramid
max = (each * 2) - 1
half_dots = int((max - 1) / 2)
base_x = 1
loc = each - 1
#For loop that appends the max. number of dots to rows depending on data in empty_rows
for every in range(empty_rows[loc]):
decks[every].append(max * '.')
#Primary for loop; appends the dots and xs to any row not covered by the previous loop (ALl rows that do not already have max dots) for each between 1-5
for i in range(each):
decks[i + empty_rows[loc]].append(half_dots * '.')
decks[i + empty_rows[loc]].append(base_x * 'x')
decks[i + empty_rows[loc]].append(half_dots * '.')
half_dots -= 1
base_x += 2
#A loop that print out the results
for each in decks:
text = ""
for i in each:
text += i
print(text)
#Starts the program by calling the main function
main()
关于python - 在Python中将图像转换为灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034389/