根据图片识别并返回验证码

2020-05-07 14:52:48 浏览数 (1)

代码语言:javascript复制
from aip import AipOcr
from PIL import Image
import os


def is_valid_image(img_path):
    """
    判断文件是否为有效(完整)的图片
    """
    try:
        Image.open(img_path).verify()
    except Exception as e:
        e = e
        print('图片缺失或损坏')
        return False
    return True


def trans_img(img_path):
    """
    转换图片格式
    :return: True:成功 False:失败
    """
    if is_valid_image(img_path):
        try:
            img_name = img_path.split('.')[0]
            new_img_path = img_name   "(1).png"
            im = Image.open(img_path)
            im.save(new_img_path)
            im.close()
            os.remove(img_path)
            os.rename(new_img_path, img_path)
            return True
        except Exception as e:
            e = e
            print('图片转换过程异常')
            return False


APP_ID = '你的APP_ID'
API_KEY = '你的API_KEY'
SECRET_KEY = '你的SECRET_KEY'


# 调用该函数即可
def get_img_content(img_path):
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    # 转换一下图片格式
    if trans_img(img_path):
        try:
            with open(img_path, 'rb') as f:
                img_data = f.read()
            res = client.basicAccurate(img_data)
            return res
        except Exception as e:
            e = e
            print('图片传输未知错误')
            return False
    else:
        return False


if __name__ == '__main__':
    print(get_img_content('code.jpg'))

0 人点赞