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

作者: python测试开发 | 来源:发表于2019-03-16 23:10 被阅读15次

    预计本章简稿完成日期: 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")
    

    相关文章

      网友评论

        本文标题:python3测试工具开发快速入门教程4图像处理

        本文链接:https://www.haomeiwen.com/subject/tynemqtx.html