遗传算法推断图像

本文详细代码见我的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
                    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值