python数据分析人工智能机器学习软件测试Python专家之路程序员

python3测试工具开发快速入门教程4图像处理

2019-03-16  本文已影响15人  python测试开发

预计本章简稿完成日期: 2018-07-18

创建图片

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

创建图片

把下面图片转为灰度图:

lake.jpg

结果:


lake_gray.jpg

代码:

#!/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")
上一篇下一篇

猜你喜欢

热点阅读