2014-01-11 3 views
0

Я завершил этап 1 и начал фазу 2, которая требует создания функции, которая может перевернуть изображение по горизонтали. То есть, пиксель, расположенный на крайнем правом конце строки, заканчивается в крайнем левом углу строки и наоборот (не забудьте сохранить порядок RGB!). Я сделал это, но я сделал это как функцию вне класс. Мне нужно вернуть функцию обратно в класс и использовать информацию, которая уже загружена в класс. Как я могу это сделать. Мне также нужна помощь в применении всех функций (flatten red, greyscale и horizontal flip) к одному файлу и только запись полученного кода в файл после того, как будут применены все функции. Пожалуйста, имейте в виду, я только 11, поэтому я не углубленное понимание Python и редактирования изображенийКлассы в Python

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 flip_horizontal(input,output): 
     data= open(self.infile,"r") 
     datain=data.read() 
     splits=datain.split() 

     type_of_ppm = splits[0] 
     no_of_columns = splits[1] 
     no_of_rows = splits[2] 
     max_color_value = splits[3] 
     pixels = splits[4:] 
     #print pixels 

     dataout = open(output, 'w') 
     dataout.write(type_of_ppm + '\n') 
     dataout.write(no_of_columns + ' ' + no_of_rows + '\n') 
     dataout.write(max_color_value +'\n') 
     if int(no_of_columns) > 1000: 
      return "ERROR!! Number of columns is larger than what can be held in a buffer." 
     else: 
      temp_list = [] 
      for b in range(int(no_of_rows)): 
       column_list = [] 
       column_list += pixels[0:int(no_of_columns) * 3] 
       pixels = pixels[int(no_of_columns) * 3 : ] 
       temp_list.append(column_list) 
      #print temp_list 
      new_list = [] 
      for i in range(int(no_of_rows)): 
       for j in range(int(no_of_columns)): 
        new_list.append (temp_list[i][-3]) 
        new_list.append (temp_list[i][-2]) 
        new_list.append (temp_list[i][-1]) 
        temp_list[i] = temp_list[i][:-3] 
      #print new_list 
      for a in range(int(no_of_columns) * int(no_of_rows) * 3): 
       dataout.write(new_list[a] + ' ') 


    def flattenred(): 
     for colour in range (0,len(self.pixels),3): 
      self.pixels [colour]=str[0] 


    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() 
sample.flattenred() 
sample.flip_horizontal 
+0

что вы имеете в виду 'ул [0]' в коде? – zhangxaochen

ответ

0
#Create a 2d lists with the smaller lists containing the rgb values and append lists of lists 
def horizontal_flip(self): 
    if int(self.columns) > 1000: 
     return "ERROR!! Number of columns is larger than what can be held in a buffer." 
    else: 
     temp_list = [] 
     for b in range(int(self.row)): 
      column_list = [] 
      column_list += self.pixels[0:int(self.columns) * 3] 
      self.pixels = self.pixels[int(self.columns) * 3 : ] 
      temp_list.append(column_list) 
     #print temp_list 
     new_list = [] 
     for i in range(int(len(temp_list))): 
      new_list.append (temp_list[i][0]) 
      new_list.append (temp_list[i][1]) 
      new_list.append (temp_list[i][2]) 
      temp_list[i] = temp_list[i][::-1] 
1

Я собираюсь пройти первую часть программы, и показать вам, как это сделать Работа. Затем вы можете применить то, что я покажу вам в остальной части программы. Я вставил ваш код ниже, и я добавлю комментарии над строками, которые нужно изменить.

class PPM(object): 
    def __init__(self, infile, outfile): 
     self.infile=infile 
     self.outfile=outfile 

     #Read in data of image 

     #!!! If you want `data` to be accessible from other functions in 
     #!!! the class you need to use `self.data`. You can then define 
     #!!! other functions using `def my_cool_function(self):, and access 
     #!!! it using `self.data`. 
     #!!! The corrected line is as follows: 

     #self.data = open(self.infile, "r") 
     data= open(self.infile,"r") 

     #!!! Similarly, you should use `self.datain` and `self.splits` 
     #!!! instead of `datain` and `splits`. i.e. 

     #self.datain=data.read() 
     #self.splits=datain.split() 

     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:] 


    #!!! Here you need to pass `self` as an argument of the function 
    #!!! Otherwise, you won't be able to access the attributes you defined 
    #!!! earlier in the `__init__()` function. 

    #def greysscale(self): 

    def greysscale(): 

      #!!! This line is indented 8 spaces, but your other indentations 
      #!!! are only 4 spaces. Python is very fussy about consistent 
      #!!! indentation. You should "dedent" this line (and the five 
      #!!! following lines) in order to maintain a consistent 4 space 
      #!!! indent. (Example is shown after this section.) 
      #!!! Also, `rows` should be `self.row` 
      for row in range(rows): 

       #!!! `columns` should be `self.columns` 
       for column in range(columns): 


        #!!! Where did you define image? 
        #!!! If it was outside the class, you will need to 
        #!!! pass it to the class in the `__init__()` function, 
        #!!! and use `self.image.getPixel`. 
        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)) 

     #!!! Corrected (but commented out) example. 
     #for row in range(self.row): 
     # for column in range(self.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)) 

Когда вы закончите исправлять его, в соответствии с моими комментариями выше, вы должны в конечном итоге с чем-то вроде этого:

class PPM(object): 
    def __init__(self, infile, outfile): 
     self.infile=infile 
     self.outfile=outfile 

     #Read in data of image 
     self.data = open(self.infile, "r") 
     self.datain=data.read() 
     self.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(self): 
     for row in range(self.row): 
      for column in range(self.columns): 

       #!!! You will still have to fix `image`. 
       #!!! I don't know how/where you defined it, so 
       #!!! I can't show you how to fix it. 
       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 my_cool_function(self, other, arguments): # NOTE `self` is first! 
    print("I am so cool.") 
    print(self.name, "is so cool too.") # Assume `self.name` was defined in 
             # the `__init__()` function. 
Смежные вопросы