图片进化(待完成)

  1 import random
  2 from PIL import Image
  3 from copy import deepcopy
  4 
  5 
  6 img_chrome = Image.open('chrome.png')
  7 h_chrome = img_chrome.size[1]
  8 w_chrome = img_chrome.size[0]
  9 
 10 
 11 img = Image.open('test1.png')
 12 h = img.size[1]
 13 w = img.size[0]
 14 
 15 
 16 img_color = []
 17 img_color_chrome = []
 18 
 19 
 20 def info_pic():  # 获取图片信息
 21 
 22     for x in range(w):
 23 
 24         img_color_tmp = []  # 先获得每一列rgb信息
 25         for y in range(h):
 26 
 27             r, g, b = img.getpixel((x, y))[:3]
 28             # print(r,g,b)
 29             img_color_tmp.append([r, g, b])
 30         img_color.append(img_color_tmp)
 31 
 32     print(img_color)
 33     print(img.size)
 34     return img_color, img.size
 35 
 36 
 37 def info_chrome():  # 获取图片信息
 38 
 39     for x in range(w_chrome):
 40 
 41         img_color_tmp = []  # 先获得每一列rgb信息
 42         for y in range(h_chrome):
 43 
 44             r, g, b = img_chrome.getpixel((x, y))[:3]
 45             # print(r,g,b)
 46             img_color_tmp.append([r, g, b])
 47         img_color_chrome.append(img_color_tmp)
 48 
 49     # print(img_color_chrome)
 50     print(img_chrome.size)
 51     return img_color_chrome, img_chrome.size
 52 
 53 
 54 # info_chrome()
 55 # print(img_color_chrome[10][10][0])
 56 
 57 population = []
 58 
 59 
 60 def initial_population(number=300):  # 编码
 61 
 62     for i in range(number):
 63         chromosome = []
 64         for x in range(w):
 65             row = []
 66             for y in range(h):
 67                 r = random.randint(0, 255)
 68                 g = random.randint(0, 255)
 69                 b = random.randint(0, 255)
 70                 row.append([r, g, b])
 71             chromosome.append(row)
 72         population.append(chromosome)
 73     print("随机基因初始化完成")
 74     return population
 75 
 76 # initial_population()
 77 # info_chrome()
 78 
 79 
 80 def fitness(chromosome):  # 计算适应度函数
 81     print("开始处理基因")
 82     
 83     diff = 0
 84     # for index1, item1 in enumerate(population):
 85 
 86     for index2, item2 in enumerate(chromosome):  # chromosome , index2表示图片的第几列
 87 
 88             for index3, item3 in enumerate(item2):  # row,index3表示某一列的第几行
 89 
 90                 for index4, item4 in enumerate(item3):  # 像素值,index4表示rgb的位置
 91                     
 92 
 93                     diff += abs(img_color_chrome[index2][index3][index4]-item4)
 94     print(diff)
 95     return diff
 96 
 97 def population_fitness(population):
 98     for index1, item1 in enumerate(population):
 99         fitness(item1)
100 
101 
102 # fitness(population[1])
103 
104 class ga(object):
105     def __init__(self,population):
106         pass
107 
108     def evolution(self, retain_rate=0.3, random_select_rate=0.5, mutation_rate=0.01):
109         """
110         对当前种群依次进行选择、交叉并生成新一代种群,然后对新一代种群进行变异
111         """
112         parents = self.selection(retain_rate, random_select_rate)
113         self.crossover(parents)
114         self.mutation(mutation_rate)
115 
116     def selection(self, retain_rate, random_select_rate):
117         graded = [(fitness(chromosome), chromosome) for chromosome in population]
118         sort = [x[1] for x in sorted(graded)]  # 正向排序
119         retain_length = int(len(sort) * retain_rate)
120         # 选出适应性强的个体,精英选择
121         parents = sort[:retain_length]
122         for chromosome in sort[retain_length:]:
123             if random.random() < random_select_rate:
124                 parents.append(chromosome)
125         return parents
126 
127     def crossover(self, parents,population):  # 交叉
128         children = []
129         # 需要繁殖的子代数量
130         target_number = len(population) - len(parents)
131         # 开始繁殖
132         while len(children) < target_number:
133             father = random.randint(0, len(parents) - 1)  # 选择交叉父代
134             mother = random.randint(0, len(parents) - 1)  # 选择交叉母代
135             if father != mother:
136                 # 随机选取交叉点
137                 cross_point_x = random.randint(0, w)
138                 cross_point_y = random.randint(0, h)
139 
140                 new_gene = deepcopy(population[father][0][:cross_point_x])
141                 new_gene = [new_gene, 0]
142                 new_gene[0][cross_point_x:] = deepcopy(population[mother][0][cross_point_x:])
143                 new_gene[0][cross_point_x][:cross_point_y] = deepcopy(population[father][0][cross_point_x][:cross_point_y])
144             children.append(new_gene)
145                 # 经过繁殖后,孩子和父母的数量与原始种群数量相等,在这里可以更新种群。
146         population = parents + children
147 
148     def variation(genes, size):
149         rate = 0.5
150         print("开始变异")
151         for i, gene in enumerate(genes):
152             for x, row in enumerate(gene[0]):
153                 for y, col in enumerate(row):
154                     if random.randint(1, 100) / 100 <= rate:
155                         # 图片由 r g b 三种颜色混合而成 变异就是改变他们的值
156                         # a b c 分别对应 r_ g_ b_ 改变的值 可自行修改
157                         # r g b 的最大值为255
158                         # ------------------------------请修改这里-------------------------------------#
159                         a = [-1, 1][random.randint(0, 1)] * random.randint(3, 10)
160                         b = [-1, 1][random.randint(0, 1)] * random.randint(3, 10)
161                         c = [-1, 1][random.randint(0, 1)] * random.randint(3, 10)
162                         # ------------------------------请修改这里-------------------------------------#
163                         genes[i][0][x][y][0] += a
164                         genes[i][0][x][y][0] += b
165                         genes[i][0][x][y][0] += c
166                         genes[i][0][x][y][3] += a + b + c
167         print("变异结束")
168 
169     def result(self):
170         '''
171         获得近优值
172         '''
173         graded = [(self.fitness_function(chromosome), chromosome) for chromosome in self.population]
174         graded = [x[1] for x in sorted(graded, reverse=True)]
175         # print('近优的x值为:', self.decode(graded[0]),
176         #       '近优的y值为:', self.fitness_function(graded[0]))
177         # 将每一步迭代的结果存储到列表中
178         y_label.append(self.fitness_function(graded[0]))
179         return self.decode(graded[0])
180 
181     def iteration(self, iter_number):
182         for i in range(iter_number):
183             self.evolution()
184             self.result()
185             x_label.append(i)

 

posted @ 2018-03-23 19:39  最后的绝地武士  阅读(253)  评论(0编辑  收藏  举报