#coding=utf-8
#轮盘赌适应度评价
from PIL import Image,ImageDraw
from const import *
import Encoding
import random
pic_aim = Image.open("image.png")
pic_aim_pixel = pic_aim.load()
ims = [n for n in range(PIC_N)]
def get_score(pic):
# 分数应该位于0-765,分数越大,品质越差
score = 0
pic_pixel = pic.load()
for i in range(WIDTH):
for j in range(HEIGHT):
score += ((pic_aim_pixel[i,j][0] - pic_pixel[i,j][0])**2
+ (pic_aim_pixel[i, j][1] - pic_pixel[i, j][1])**2
+ (pic_aim_pixel[i, j][2] - pic_pixel[i, j][2])**2)###
return score/255/255
def get_fitness(pic):
pic.draw_it()
score = get_score(pic.img)
fitness = (195075 - score)
return fitness
def get_lfit(lst):
# 获取适应度及适应度累计值
max = 0
ft = 0
_lst = lst
for i in range(NUM):
_lst[i].draw_it()
_lst[i].score = get_score(_lst[i].img)
if _lst[i].score > max :max = _lst[i].score
_lst[i].fitness = 0
_lst[i].fitness_total = 0
for i in range(NUM):
_lst[i].fitness = (195075 - _lst[i].score)
ft += _lst[i].fitness
_lst[i].fitness_total = ft
lst = _lst
return lst,ft
def fitness_sort(lst):
return sorted(lst, key=lambda key: key.fitness)
def sort(lst):
lst, max = get_lfit(lst)
b_ft = 0
w_ft = 2000000
best = 0
worst = 0
for i in range(NUM):
if lst[i].fitness > b_ft:
b_ft = lst[i].fitness
best = i
if lst[i].fitness < w_ft:
w_ft = lst[i].fitness
worst = i
lst[worst] = Encoding.pic(lst[best].gens)
return lst
def rlt_sorted(lst):
#轮盘赌
_lst = []
lst = sort(lst)
lst = sort(lst)
lst,max = get_lfit(lst)
for i in range(NUM):
rd = random.randrange(0,max)
for j in range(NUM):
if rd >= lst[j].fitness_total and rd <= lst[j+1].fitness_total :
temp = Encoding.pic(lst[j+1].gens)
# temp = copy.deepcopy(lst[j+1])#####
_lst.append(temp)
break
elif rd <= lst[0].fitness_total:
temp = Encoding.pic(lst[0].gens)
# temp = copy.deepcopy(lst[0])#####
_lst.append(temp)
break
return _lst
# def insert_sort(lst):
##插入排序
# for i in range(1,len(lst)):
# tmp = lst[i].fitness
# k = i-1
# while(k > 0 and tmp < lst[k].fitness):
# lst[k+1] = lst[k]
# k -= 1
# lst[k+1] = tmp
评论0
最新资源