預計本章簡稿完成日期: 2018-07-18
創(chuàng)建圖片
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術支持 釘釘群:21745728(可以加釘釘pythontesting邀請加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-12
# dutchflag.py
from PIL import Image
def dutchflag(width, height):
"""Return new image of Dutch flag."""
img = Image.new("RGB", (width, height))
for j in range(height):
for i in range(width):
if j < height/3:
img.putpixel((i, j), (255, 0, 0))
elif j < 2*height/3:
img.putpixel((i, j), (0, 255, 0))
else:
img.putpixel((i, j), (0, 0, 255))
return img
def main():
img = dutchflag(600, 400)
img.save("dutchflag.jpg")
main()
創(chuàng)建圖片
把下面圖片轉為灰度圖:
結果:
代碼:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術支持 釘釘群:21745728(可以加釘釘pythontesting邀請加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-12
# grayscale.py
from PIL import Image
def grayscale(img):
"""Return copy of img in grayscale."""
width, height = img.size
newimg = Image.new("RGB", (width, height))
for j in range(height):
for i in range(width):
r, g, b = img.getpixel((i, j))
avg = (r + g + b) // 3
newimg.putpixel((i, j), (avg, avg, avg))
return newimg
def main():
img = Image.open("lake.jpg")
newimg = grayscale(img)
newimg.save("lake_gray.jpg")
main()
實際應用中趁蕊,convert方法已經幫我們做好了這些,參見grayscale2.py
代碼:
#!/usr/bin/env python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術支持 釘釘群:21745728(可以加釘釘pythontesting邀請加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-12
# grayscale2.py
from PIL import Image
Image.open("lake.jpg").convert("L").save("lake_gray.jpg")