python生成曼德勃罗分形图形

来自https://blog.csdn.net/baimafujinji/article/details/50859174

c程序版生产那种格式的图像显然不利于咱们研究分析,于是写个py版本的以方便学习。

用到了PIL的Image库来生成RGB图像,转化为numpy数组来进行像素值操作,显示用到matplotlib。

根据曼德勃罗集合迭代式,计算当前坐标是否满足条件来修改像素值,根据定理

,则

,ok我们迭代后满足条件的像素置灰。

准备就绪,附上代码

import time
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

wid_size = 1920
hei_size = 1080
maxVal = 255
orig_x = wid_size*2/3
orig_y = hei_size/2

def iteration(x,y):
    limit = maxVal + 1
    A = (x-orig_x)/(wid_size/3)
    B = (orig_y-y)/(hei_size/2)
    c = complex(A,B)
    z = complex(0,0)
    for i in range(limit):
        z = z * z + c
        if z.real>2 or z.imag>2:
            break
    return 0 if i==maxVal else 1

if __name__ == '__main__':
    img = Image.new('RGB',(wid_size,hei_size))
    #img.shape
    imgp = np.array(img)
    t0 = time.perf_counter()
    for i in range(hei_size):
        for j in range(wid_size):
            ite = iteration(j,i)
            if ite:
                imgp[i,j,0] = ite
                imgp[i,j,1] = abs(j-orig_x)/wid_size*maxVal
                imgp[i,j,2] = abs(i-orig_y)/hei_size*maxVal
            else:
                imgp[i,j,:] = 128
    
    t1 = time.perf_counter()
    print(t1-t0)
    plt.imshow(imgp)
    plt.show()
    img = Image.fromarray(imgp)
    img.save('./1.jpg')

不试不知道,一试吓一跳,速度感人。。。

用了100秒,是的,效率极其低下。。。虽然写代码很方便,但还是改成c++试试吧

BYTE *imgs = new BYTE[width_size*height_size * 3];
memset(imgs, 0, width_size*height_size * 3);
double t0 = clock();
for (int i = 0; i < height_size; i++) {
	for (int j = 0; j < width_size; j++) {
		BYTE ite = iteration(j, i);
		//BGR反位写入
		if (ite) {
			imgs[(i*width_size + j) * 3 + 2] = ite;
			imgs[((i + 0)*width_size + j) * 3 + 1] = abs(j - orig_x) / width_size * Maxval;
			imgs[((i + 0)*width_size + j) * 3 + 0] = abs(i - orig_y) / height_size * Maxval;
			}
		else {
			imgs[(i*width_size + j) * 3] = 128;
			imgs[((i + 0)*width_size + j) * 3 + 1] = 128;
			imgs[((i + 0)*width_size + j) * 3 + 2] = 128;
		}
	}
}
double t1 = clock();
cout << t1 - t0 << endl;
saveBitmap(width_size, height_size, imgs, width_size * height_size * 3, "1.bmp");

好的,run一下,震惊,三秒,快了30倍,是的,嘻嘻,c++还是强的。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值