zoukankan      html  css  js  c++  java
  • Python摄像头抓拍的彩色图像转为灰度图、二值化和调整图片尺寸(实例)

    实现代码

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    from PIL import Image
    import cv2
    import numpy as np
    
    
    def aikit_take_pictures():   # 调用摄像头,并保存图像函数
        camera = cv2.VideoCapture(0)
        while True:
            ret, frame = camera.read()  # 一帧一帧读取视频
            cv2.imshow('frame', frame)  # 显示结果
            # 根据用户的键盘操作,保存照片或者停止程序
            key_code = cv2.waitKey(1)
            if key_code & 0xFF == ord('p'):  # 按p保存照片
                cv2.imwrite("photo.jpg", frame)
                print('Successful photo')
            if key_code & 0xFF == ord('q'):  # 按q停止
                break
            
        camera.release()
        cv2.destroyAllWindows()
    
    
    def Image_resize():   # 裁剪图片大小函数
    	img = Image.open('photo.jpg')   # 需要转换的源图片,前提是该图片已经在上一个函数中保存
    	outsize = img.resize((100,88), Image.ANTIALIAS)  # 设置输出图片的大小
    	outsize.save('resize.png','png')  # 输出图片的名字及格式
    
    
    def gray_img():       # 灰度图函数
        img = Image.open('photo.jpg')  # 需要转换的源图片,前提是该图片已经在上一个函数中保存
        Img = img.convert('L')  # PIL有九种不同模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。这里选择L灰度模式
        Img.save("gray.jpg")  # 保保存文件名
    
    def binary_scale():    # 二值化函数
        img = Image.open('photo.jpg')
        Img = img.convert('L') # PIL有九种不同模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。这里选择L灰度模式
        threshold = 200   # 设定的阈值
        table = []  
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        photo = Img.point(table, '1')
        photo.save('binary.jpg')
    
    
    if __name__ == '__main__':   # 调用函数
        aikit_take_pictures()   
        Image_resize()
        gray_img()
        binary_scale()
        pass
    

    提醒:
    有的小伙伴可能会在运行时,出现代码报错,此时需要注意的是,记得环境要安装正确或者包要导对哦~
    有需要帮助的可以查看本博客内容,选择所需就好,或者在下方留言

  • 相关阅读:
    php过滤表单提交的html等危险代码
    浅析php过滤html字符串,防止SQL注入的方法
    PHP简单判断手机设备的方法
    如何用Math.max.apply()获取数组最大/小值
    Ubuntu14.04升级到Ubuntu16.04
    4、python数据类型之列表(list)
    3、python数据类型之字符串(str)
    centos7网卡名称修改以及配置
    rsync简单总结
    8、kvm虚拟机添加硬盘
  • 原文地址:https://www.cnblogs.com/hleisurely/p/13341204.html
Copyright © 2011-2022 走看看