DDA瞎g2写的,对不对也不知道,Bresenham是老师的代码

from PIL import Image
import random
import time

def DDA(img,x0,y0,x1,y1,color):
    dx=x1-x0
    dy=y1-y0
    if x0!=x1:
        m=dy/dx

    if x1==x0:
        for y in range(y0,y1 + 1):
            img.putpixel((x0, y), color)

    elif abs(m)<=1:
        y = y0
        for x in range(x0, x1 + 1):
            img.putpixel((x, int(y+0.5)), color)
            y=y+m
    else:
        m=1/m
        x=x0
        for y in range(y0,y1 + 1):
            img.putpixel((int(x+0.5), y), color)
            x=x+m

def Bresenham(img, x0, y0, x1, y1, color):
    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0,y0=y0,x0
        x1,y1=y1,x1
    if x0 > x1:
        x0,x1=x1,x0
        y0,y1=y1,y0
    if y0 > y1:
        t = -1
    else:
        t = 1
    xx = x1 - x0
    yy = abs(y1 - y0)
    y = y0
    error = 0
    for x in range(x0, x1 + 1):
        if steep:
            img.putpixel((y, x), color)
        else:
            img.putpixel((x, y), color)
        error = error + yy
        if 2 * error >= xx:
            y = y + t
            error = error - xx

img1=Image.new("RGB",(300,300))
img2 = Image.new("RGB", (300, 300))

start = time.time()

for i in range(1000):
    x0 = random.randint(0, 299)
    y0 = random.randint(0, 299)
    x1 = random.randint(0, 299)
    y1 = random.randint(0, 299)
    DDA(img1, x0, y0, x1, y1, (255, 0, 0))

tb = time.time() - start
print("DDA:", tb)
start = time.time()
for i in range(1000):
    x0 = random.randint(0, 299)
    y0 = random.randint(0, 299)
    x1 = random.randint(0, 299)
    y1 = random.randint(0, 299)
    Bresenham(img2, x0, y0, x1, y1, (255, 0, 0))

tb = time.time() - start
print("Bresenham:", tb)

img1.show()
img2.show()

Last modification:October 11th, 2020 at 09:16 pm