本文详细代码见我的github仓库 AI_ML_DataAnalysis_DataVisualization_Classic-Examples
icon_genetic.py
# -*- coding: utf-8 -*-
from __future__ import division
from PIL import Image as im
from random import randint
from copy import deepcopy
import pickle as pk
global_variable = {
}
# 图片预处理
def process_pic(pic_name):
print("正在初始化图片,将图片转换为颜色矩阵...")
# 获得图片对象
img = im.open(pic_name)
# 获得图片的规格
img_color = []
img_width, img_height = img.size
for x in range(img_height):
img_color_tmp = []
for y in range(img_width):
# 图片的RGB
r, g, b = img.getpixel((y, x))[:3]
# 将RGB转10进制
img_color_tmp.append((r, g, b, r + g + b))
img_color.append(img_color_tmp)
print("图片转化为颜色矩阵已完成")
return img_color, img.size
# 随机产生第一代基因
def random_genes():
print("当前图片尺寸:" + str(size))
print("随机产生图像基因...")
width, height = size
genes = []
for i in range(100):
gene = []
for x in range(height):
row = []
for y in range(width):
a = randint(0, 255)
b = randint(0, 255)
c = randint(0, 255)
row.append([a, b, c, a + b + c])
gene.append(row)
genes.append([gene, 0])
print("图像基因已创建完毕...")
return genes
# 定义适应度计算函数
def forecast():
print("正在考察基因适应度...")
sum_sum = 0
for i, gene in enumerate(genes):
sum_ = 0
for j, row in enumerate(gene[0]):
for k, col in enumerate(row):
_a, _b, _c, _d = data[j][k]
a, b, c, d = col
det_d = abs(_d - d)
sum_ += (abs(_a - a) + abs(_b - b) + abs(_c - c)) * det_d
genes[i][1] = sum_
sum_sum += sum_
for i, gene in enumerate(genes):
genes[i][1] = genes[i][1] / sum_sum
print("基因正在排序...")
genes.sort(key=lambda x: x[1])
print("基因排序完成...")
return
# 基因变异函数
def variation():
rate = 0.5
for i, gene in enumerate(genes):
for x, row in enumerate(gene[0]):
for y, col in enumerate(row):
is_gene_mutation = False
if randint(1, 100) / 100.0 <= rate:
is_gene_mutation = True