2017-02-10 90 views
-1
from PIL import Image 
import time 
start = time.time() 
import random as r 
x = int(input("Enter the preferred width of your image:")) 
y = int(input("Enter the preferred length of your image:")) 
suggested = (x*y) 
print("We suggest you use:",suggested,"pixels") 
amount = int(input("How many pixels do you want to generate?")) 
while amount > suggested: 
    amount = int(input("Please choose the number suggested or smaller.  How many pixels do you want to generate?")) 
numbers = [] 
numbs = (r.randint(0,255),r.randint(0,255),r.randint(0,255)) 
while len(numbers)<(amount): 
    numbers.append(numbs) 
    numbs = (r.randint(0,255),r.randint(0,255),r.randint(0,255)) 
print(numbers) 
print('It took', time.time()-start, 'seconds') 
im2 = Image.new('RGB', (x,y)) 
im2.putdata(numbers) 
im2.show() 
im2.save("out.png") 

我使用的代碼將三個隨機數字放入一個元組中,然後將該元組放入列表中。每個元組都是一個像素。用戶輸入的尺寸總是形成一個直的形狀,寬x長,我想使形狀變圓並具有彎曲的邊緣。怎麼樣?謝謝。如何讓形狀創建一個圓形?

回答

0

我玩你的代碼,並能夠添加一個開放的綠色圓圈和一個藍色的實心圓。試試看:

from PIL import Image, ImageDraw 
import time 
import math 
# 
start = time.time() 
import random as r 
#x = int(input("Enter the preferred width of your image:")) 
x = 100 
#y = int(input("Enter the preferred length of your image:")) 
y = 150 
suggested = (x*y) 
print("We suggest you use:",suggested,"pixels") 
#amount = int(input("How many pixels do you want to generate?")) 
amount = 15000 
while amount > suggested: 
    amount = int(input("Please choose the number suggested or smaller.  How many pixels do you want to generate?")) 
numbers = [] 
numbs = (r.randint(0,255),r.randint(0,255),r.randint(0,255)) 
while len(numbers)<(amount): 
    numbers.append(numbs) 
    numbs = (r.randint(0,255),r.randint(0,255),r.randint(0,255)) 
print(numbers) 
# 
print('It took', time.time()-start, 'seconds') 
im2 = Image.new('RGB', (x,y)) 
im2.putdata(numbers) 
#----------------------------------------------------------- 
numb_test = (255,0,0) # red circle 
numb_test = (0,255,0) # green circle 
radius_test = min(x,y) * 0.4 
print "radius_test = " + str(radius_test) 
x_center = x/2 
y_center = y/2 
angle_test = 0 
print "pi = " + str(math.pi) 
while angle_test < 360: 
    angle_rads = angle_test * math.pi/180.0 
    x_test = int(radius_test * math.cos(angle_rads)) + x_center 
    y_test = int(radius_test * math.sin(angle_rads)) + y_center 
    #print "x_test, y_test = " + str(x_test) + ", " + str(y_test) 
    im2.putpixel((x_test, y_test),numb_test) 
    angle_test += 1 
# 
draw = ImageDraw.Draw(im2) 
draw.ellipse((20, 20, 40, 40), fill = 'blue', outline ='blue') 
#----------------------------------------------------------- 
im2.show() 
im2.save("out.png") 

請注意,ImageDraw也從PIL導入和數學導入。 我發現了繪製這裏描述的橢圓的方法: http://effbot.org/imagingbook/imagedraw.htm

相關問題