python3測試工具開發快速入門教程4圖像處理

預計本章簡稿完成日期: 2018-07-18

創建圖片

#!/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()

創建圖片

把下面圖片轉爲灰度圖:

結果:


代碼:

#!/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")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章