研究了下Bringing Old Photo Back to Life的开源代码,觉得还不错,从链接中看到了https://github.com/jantic/DeOldify 这个开源库 :给黑白照片着色。没时间研究它的源代码了,找到了Deepai,有几个api就拿来试了试效果:

import re
import requests


def image_colorization(input_img, output_img):
    """
    图像着色:黑白照片着色等
    :param input_img: 可以是url或本地路径
    :param output_img: 着色后输出的路径
    :return:
    """
    # 为图像着色
    # api_url = 'https://api.deepai.org/api/colorizer'
    # 美化(变卡通)
    # api_url = 'https://api.deepai.org/api/toonify'
    # 超分辨率
    # api_url = 'https://api.deepai.org/api/torch-srgan'
    api_key = '95ce4e5d-d7d3-43f5-a37c-de2ee3b4548c'
    headers = {
        'api-key': api_key
    }

    # 使用正则判断input_img是否是url
    regex = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    print(re.match(regex, "http://www.example.com") is not None)  # True
    print(re.match(regex, "example.com") is not None)             # False
    if re.match(regex, input_img) is not None:
        data = {'image': input_img}
        response = requests.post(url=api_url, headers=headers, data=data)
    else:
        files = {'image': open(input_img, 'rb')}
        response = requests.post(url=api_url, headers=headers, files=files)
    print(type(response.json()), response.json())

    output_url = response.json()['output_url']
    response = requests.get(output_url).content
    with open(output_img, 'wb') as fp:
        fp.write(response)


if __name__ == '__main__':

    image_colorization('images/0_1.png', 'images/new/out.jpg')

 

 当然实际使用还要看原始图片的像素大小等等问题。具体可以查看官网

https://deepai.org/machine-learning-model/colorizer

posted on 2021-08-27 21:34  FilexHu  阅读(353)  评论(0编辑  收藏  举报